File size: 6,225 Bytes
a65f762 | 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 | #!/usr/bin/env python
"""
Compare QE band structure with HPRO real-space reconstruction for diamond.
Reads:
- data/bands/kpath.json (k-path from prepare.py)
- data/bands/{uc,sc}/scf/bands.dat.gnu (QE eigenvalues from bands.x)
- data/bands/{uc,sc}/reconstruction/aohamiltonian/ (HPRO H(R))
Produces band comparison plots: band_compare_uc.png and band_compare_sc.png
Usage: python compare_bands.py [params.json]
"""
import json
import os
import sys
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from scipy.linalg import eigh
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 load_kpath(data_dir):
with open(os.path.join(data_dir, 'bands', 'kpath.json')) as f:
return json.load(f)
def parse_bands_gnu(gnu_path):
"""Parse QE bands.dat.gnu: blocks separated by blank lines.
Each block corresponds to one band; each line is 'k_dist eigenvalue'.
Returns eigs (nk, nbnd) in eV (same units as bands.x output).
"""
bands, block = [], []
with open(gnu_path) as f:
for line in f:
line = line.strip()
if line:
block.append(float(line.split()[1]))
else:
if block:
bands.append(block)
block = []
if block:
bands.append(block)
if not bands:
raise FileNotFoundError(f"No data found in {gnu_path}")
return np.array(bands).T # (nk, nbnd)
def compute_hpro_bands(aodir, kpts_all, x_arr, nbnd):
"""Compute band structure from HPRO H(R) via direct Fourier transform.
Uses load_deeph_HS + scipy.eigh for each k-point.
Hermitianizes H(k) (not H(R)) before diagonalizing.
Returns:
eigs (nk, nbnd) eigenvalues in eV, aligned to kpts_all
"""
from HPRO.deephio import load_deeph_HS
from HPRO.constants import hartree2ev
matH = load_deeph_HS(aodir, 'hamiltonians.h5', energy_unit=True)
matS = load_deeph_HS(aodir, 'overlaps.h5', energy_unit=False)
matS.hermitianize() # S(R) is exact, hermitianize in real space
nk = len(kpts_all)
eigs_all = np.empty((nk, nbnd))
print(f" Diagonalizing at {nk} k-points...")
for ik, kpt in enumerate(kpts_all):
if ik % 50 == 0:
print(f" k-point {ik}/{nk}")
Hk = matH.r2k(kpt).toarray()
Sk = matS.r2k(kpt).toarray()
Hk = 0.5 * (Hk + Hk.conj().T) # hermitianize H(k) only
eigs_k, _ = eigh(Hk, Sk)
eigs_all[ik] = eigs_k[:nbnd] * hartree2ev
return eigs_all
def plot_comparison(x, eigs_qe, eigs_hpro, x_hs, labels, title, outpath):
"""Plot QE vs HPRO band structures (both pre-aligned to their own VBM)."""
fig, ax = plt.subplots(figsize=(6, 5))
for ib in range(eigs_qe.shape[1]):
ax.plot(x, eigs_qe[:, ib], 'b-', lw=1.2, alpha=0.8,
label='QE' if ib == 0 else '')
for ib in range(eigs_hpro.shape[1]):
ax.plot(x, eigs_hpro[:, ib], 'r--', lw=1.0, alpha=0.8,
label='HPRO' if ib == 0 else '')
for xv in x_hs:
ax.axvline(xv, color='k', lw=0.8, ls='--')
ax.axhline(0, color='k', lw=0.5, ls=':')
ax.set_xticks(x_hs)
ax.set_xticklabels(labels, fontsize=11)
ax.set_ylabel('Energy (eV)', fontsize=11)
ax.set_xlim(x[0], x[-1])
emax = max(np.max(eigs_qe), np.max(eigs_hpro))
emin = min(np.min(eigs_qe), np.min(eigs_hpro))
ax.set_ylim(emin - 1, emax + 1)
ax.set_title(title, fontsize=11)
ax.legend(fontsize=10)
fig.tight_layout()
fig.savefig(outpath, dpi=200)
plt.close(fig)
print(f" Saved: {outpath}")
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)
data_dir = os.path.join(SCRIPT_DIR, 'data')
kpath = load_kpath(data_dir)
kpts_hs = np.array(kpath['kpts_hs'])
npts = kpath['npts']
labels = kpath['labels']
x_ref = np.array(kpath['x'])
x_hs = kpath['x_hs']
for cell_label in ('uc', 'sc'):
bands_dir = os.path.join(data_dir, 'bands', cell_label)
scf_dir = os.path.join(bands_dir, 'scf')
aodir = os.path.join(bands_dir, 'reconstruction', 'aohamiltonian')
if not os.path.exists(os.path.join(aodir, 'hamiltonians.h5')):
print(f"[{cell_label}] HPRO hamiltonians.h5 not found, "
"run reconstruct.py first")
continue
gnu = os.path.join(scf_dir, 'bands.dat.gnu')
if not os.path.exists(gnu):
print(f"[{cell_label}] bands.dat.gnu not found ({gnu}), "
"run run.py first")
continue
print(f"\n[{cell_label}] Loading QE bands from bands.dat.gnu...")
eigs_qe = parse_bands_gnu(gnu)
# VBM: highest occupied level
n_occ = 4 if cell_label == 'uc' else 4 * 8 # 4 electrons per UC
rec = params['reconstruction']
nbnd_param = rec.get('nbnd_sc', rec['nbnd']) if cell_label == 'sc' else rec['nbnd']
print(f"[{cell_label}] Computing HPRO bands...")
kpts_all = np.array(kpath['kpts_all'])
eigs_hpro = compute_hpro_bands(aodir, kpts_all, x_ref, nbnd_param)
# Align each source independently to its own VBM
nbnd_cmp = min(nbnd_param, eigs_qe.shape[1], eigs_hpro.shape[1])
vbm_qe = np.max(eigs_qe[:, :n_occ])
vbm_hpro = np.max(eigs_hpro[:, :n_occ])
eigs_qe_al = eigs_qe[:, :nbnd_cmp] - vbm_qe
eigs_hpro_al = eigs_hpro[:, :nbnd_cmp] - vbm_hpro
mae = np.mean(np.abs(eigs_qe_al - eigs_hpro_al))
print(f"[{cell_label}] MAE (first {nbnd_cmp} bands, VBM-aligned) = "
f"{mae*1000:.1f} meV")
outpath = os.path.join(SCRIPT_DIR, f'band_compare_{cell_label}.png')
title = f'Diamond {cell_label.upper()}: QE vs HPRO reconstruction'
plot_comparison(x_ref, eigs_qe_al, eigs_hpro_al,
x_hs, labels, title, outpath)
print("\ncompare_bands.py done.")
if __name__ == '__main__':
main()
|