File size: 11,743 Bytes
d975267
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
#!/usr/bin/env python
"""Compare QE, HPRO, and ML (DeepH-E3) band structures for diamond.

Processes both the pristine unit cell (UC) and pristine 2×2×2 supercell (SC).
For each cell, runs DeepH-E3 inference and plots QE / HPRO / ML bands.

Outputs: band_compare_uc_ml.png, band_compare_sc_ml.png

Usage: python compare_bands.py [params.json]
"""
import glob
import json
import os
import subprocess
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__))
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'))
RESULTS_DIR    = os.path.join(SCRIPT_DIR, 'results')


def load_params(path=None):
    with open(path or PARAMS_DEFAULT) as f:
        return json.load(f)


def find_latest_model():
    """Return path to the latest trained model directory in results/."""
    dirs = sorted(glob.glob(os.path.join(RESULTS_DIR, '*')))
    dirs = [d for d in dirs if os.path.isdir(d)
            and os.path.exists(os.path.join(d, 'best_model.pkl'))]
    return dirs[-1] if dirs else None


def infer_paths(cell_label):
    """Return (dataset_dir, graph_dir, output_dir, ini_path) for cell_label."""
    base = os.path.join(SCRIPT_DIR, f'infer_{cell_label}')
    return (
        os.path.join(base, 'dataset'),
        os.path.join(base, 'graph'),
        os.path.join(base, 'output'),
        os.path.join(base, 'eval.ini'),
    )


def build_infer_dataset(aodir, dataset_dir):
    """Create dataset_dir/00/ with per-file symlinks to aodir."""
    dest = os.path.join(dataset_dir, '00')
    os.makedirs(dest, exist_ok=True)
    for fname in os.listdir(aodir):
        link = os.path.join(dest, fname)
        if not os.path.exists(link):
            os.symlink(os.path.join(aodir, fname), link)
    print(f'  Inference dataset ready: {dest}')


def write_eval_ini(ini_path, model_dir, dataset_dir, graph_dir, output_dir,
                   dataset_name, params):
    """Write eval.ini for DeepH-E3 inference."""
    t = params.get('hamiltonian', {})
    ini = f"""; DeepH-E3 eval config — generated by compare_bands.py

[basic]
device = {t.get('device', 'cuda')}
dtype = float
trained_model_dir = {model_dir}
output_dir = {output_dir}
target = hamiltonian
inference = False
test_only = False

[data]
graph_dir =
DFT_data_dir =
processed_data_dir = {dataset_dir}
save_graph_dir = {graph_dir}
target_data = hamiltonian
dataset_name = {dataset_name}
get_overlap = False
"""
    with open(ini_path, 'w') as f:
        f.write(ini)
    print(f'  Written {ini_path}')


def run_inference(ini_path, params):
    """Launch DeepH-E3 inference in the deeph conda environment."""
    t = params.get('hamiltonian', {})
    conda_env    = t.get('conda_env', 'deeph')
    conda_base   = params['paths']['conda_base']
    deeph_e3_dir = t.get('deeph_e3_dir', '/home/apolyukhin/Development/DeepH-E3')

    launcher = os.path.join(SCRIPT_DIR, '_eval_launcher.py')
    with open(launcher, 'w') as f:
        f.write(f"""import sys, torch
torch.serialization.add_safe_globals([slice])
try:
    from torch_geometric.data.data import DataEdgeAttr, DataTensorAttr
    from torch_geometric.data.storage import GlobalStorage
    torch.serialization.add_safe_globals([DataEdgeAttr, DataTensorAttr, GlobalStorage])
except ImportError:
    pass
sys.path.insert(0, '{deeph_e3_dir}')
from deephe3 import DeepHE3Kernel
kernel = DeepHE3Kernel()
kernel.eval('{ini_path}')
""")

    activate = (f'source {conda_base}/etc/profile.d/conda.sh'
                f' && conda activate {conda_env}')
    print('  Running DeepH-E3 inference...')
    subprocess.run(['bash', '-c', f'{activate} && python {launcher}'], check=True)


def load_kpath():
    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 → (nk, nbnd) array in eV."""
    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 in {gnu_path}')
    return np.array(bands).T   # (nk, nbnd)


def compute_bands(aodir, h5_name, kpts_all, nbnd):
    """Diagonalize H(R) from h5_name in aodir along kpts_all.

    Uses the standard generalized eigenproblem eigh(Hk, Sk) matching the
    reference approach (add_qe_bands.py): hermitianize both Hk and Sk in
    k-space, then solve directly without Löwdin truncation.
    Returns (nk, nbnd) eigenvalues in eV.
    """
    from HPRO.deephio import load_deeph_HS
    from HPRO.constants import hartree2ev

    matH = load_deeph_HS(aodir, h5_name, energy_unit=True)
    matS = load_deeph_HS(aodir, 'overlaps.h5', energy_unit=False)
    matS.hermitianize()

    nk = len(kpts_all)
    eigs_all = np.empty((nk, nbnd))
    print(f'  Diagonalizing {h5_name} 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)
        Sk = 0.5 * (Sk + Sk.conj().T)   # hermitianize Sk in k-space (matches reference)
        eigs_k = np.sort(np.real(eigh(Hk, Sk, eigvals_only=True)))
        n = min(nbnd, len(eigs_k))
        eigs_all[ik, :n] = eigs_k[:n] * hartree2ev
        if n < nbnd:
            eigs_all[ik, n:] = np.nan
    return eigs_all


def plot_comparison(x, eigs_qe, eigs_hpro, eigs_ml, x_hs, labels, n_occ,
                    title, outpath, n_cond=10, ewin=20.0):
    """Plot QE (blue), HPRO (red dashed), ML (green dotted), all VBM-aligned.

    MAE is reported separately for occupied bands and the n_cond lowest
    conduction bands.  Only bands passing through [-ewin, +ewin] eV relative
    to VBM are plotted (avoids unphysical high-energy AO-basis artifacts).
    """
    vbm_qe   = np.max(eigs_qe[:, :n_occ])
    vbm_hpro = np.max(eigs_hpro[:, :n_occ])
    vbm_ml   = np.max(eigs_ml[:, :n_occ])

    nbnd_all = min(eigs_qe.shape[1], eigs_hpro.shape[1], eigs_ml.shape[1])
    eq = eigs_qe[:, :nbnd_all]  - vbm_qe
    eh = eigs_hpro[:, :nbnd_all] - vbm_hpro
    em = eigs_ml[:, :nbnd_all]  - vbm_ml

    # MAE only over occupied + n_cond lowest conduction bands
    n_cmp = min(n_occ + n_cond, nbnd_all)
    def _mae(a, b):
        d = np.abs(a - b)
        return np.nanmean(d)

    mae_hpro_occ = _mae(eq[:, :n_occ], eh[:, :n_occ])
    mae_ml_occ   = _mae(eq[:, :n_occ], em[:, :n_occ])
    mae_hpro_cond = _mae(eq[:, n_occ:n_cmp], eh[:, n_occ:n_cmp]) if n_cmp > n_occ else 0.0
    mae_ml_cond   = _mae(eq[:, n_occ:n_cmp], em[:, n_occ:n_cmp]) if n_cmp > n_occ else 0.0
    print(f'  MAE (occ)  HPRO: {mae_hpro_occ*1000:.1f} meV   ML: {mae_ml_occ*1000:.1f} meV')
    print(f'  MAE (cond) HPRO: {mae_hpro_cond*1000:.1f} meV   ML: {mae_ml_cond*1000:.1f} meV')

    fig, ax = plt.subplots(figsize=(7, 5))
    for ib in range(nbnd_all):
        bq, bh, bm = eq[:, ib], eh[:, ib], em[:, ib]
        in_win = np.any((bq > -ewin) & (bq < ewin))
        if not in_win:
            continue
        ax.plot(x, bq, 'b-',  lw=1.0, alpha=0.7, label='QE'   if ib == 0 else '')
        ax.plot(x, bh, 'r--', lw=0.9, alpha=0.7, label='HPRO' if ib == 0 else '')
        ax.plot(x, bm, 'g:',  lw=1.0, alpha=0.8, label='ML'   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])
    ax.set_ylim(-ewin, ewin)
    ax.set_title(
        title + f'\nMAE occ: HPRO={mae_hpro_occ*1000:.1f} meV  ML={mae_ml_occ*1000:.1f} meV'
              + f'  |  cond: HPRO={mae_hpro_cond*1000:.1f} meV  ML={mae_ml_cond*1000:.1f} meV',
        fontsize=9)
    ax.legend(fontsize=9)
    fig.tight_layout()
    fig.savefig(outpath, dpi=200)
    plt.close(fig)
    print(f'  Saved: {outpath}')


def process_cell(cell_label, model_dir, kpath, params):
    """Run inference + plot for one cell (uc or sc)."""
    rec = params['reconstruction']
    if cell_label == 'uc':
        nbnd  = rec['nbnd']
        n_occ = 4          # 4 valence electrons in the UC
    else:
        nbnd  = rec.get('nbnd_sc', rec['nbnd'])
        n_occ = 4 * 8      # 4 valence e⁻ × 8 UC per 2×2×2 SC

    bands_dir = os.path.join(DATA_DIR, 'bands', cell_label)
    aodir     = os.path.join(bands_dir, 'reconstruction', 'aohamiltonian')
    gnu       = os.path.join(bands_dir, 'scf', 'bands.dat.gnu')

    if not os.path.exists(os.path.join(aodir, 'hamiltonians.h5')):
        print(f'[{cell_label}] hamiltonians.h5 not found, skipping')
        return
    if not os.path.exists(gnu):
        print(f'[{cell_label}] bands.dat.gnu not found, skipping')
        return

    dataset_dir, graph_dir, output_dir, ini_path = infer_paths(cell_label)
    pred_h5   = os.path.join(output_dir, '00', 'hamiltonians_pred.h5')
    pred_link = os.path.join(dataset_dir, '00', 'hamiltonians_pred.h5')

    if not os.path.exists(pred_h5):
        print(f'[{cell_label}] Step 1: Building inference dataset...')
        build_infer_dataset(aodir, dataset_dir)
        os.makedirs(graph_dir,  exist_ok=True)
        os.makedirs(output_dir, exist_ok=True)

        print(f'[{cell_label}] Step 2: Writing eval.ini...')
        write_eval_ini(ini_path, model_dir, dataset_dir, graph_dir, output_dir,
                       dataset_name=f'diamond_qe_e3_pristine_{cell_label}',
                       params=params)

        print(f'[{cell_label}] Step 3: Running DeepH-E3 inference...')
        run_inference(ini_path, params)
    else:
        print(f'[{cell_label}] Using cached prediction: {pred_h5}')

    if not os.path.exists(pred_link):
        os.symlink(pred_h5, pred_link)

    kpts_all = np.array(kpath['kpts_all'])
    x_ref    = np.array(kpath['x'])
    x_hs     = kpath['x_hs']
    labels   = kpath['labels']

    print(f'\n[{cell_label}] Loading QE bands...')
    eigs_qe = parse_bands_gnu(gnu)

    print(f'[{cell_label}] Computing HPRO bands...')
    eigs_hpro = compute_bands(aodir, 'hamiltonians.h5', kpts_all, nbnd)

    print(f'[{cell_label}] Computing ML bands...')
    eigs_ml = compute_bands(dataset_dir + '/00', 'hamiltonians_pred.h5', kpts_all, nbnd)

    outpath = os.path.join(SCRIPT_DIR, f'band_compare_{cell_label}_ml.png')
    cell_title = 'UC' if cell_label == 'uc' else 'SC (2×2×2)'
    print(f'[{cell_label}] Plotting...')
    plot_comparison(x_ref, eigs_qe, eigs_hpro, eigs_ml, x_hs, labels, n_occ,
                    title=f'Diamond {cell_title}: QE vs HPRO vs ML (DeepH-E3)',
                    outpath=outpath)


def main():
    params_path = next((a for a in sys.argv[1:] if not a.startswith('--')), None)
    params = load_params(params_path)

    model_dir = find_latest_model()
    if model_dir is None:
        print('ERROR: No trained model found in results/. Run train_ham.py first.')
        sys.exit(1)
    print(f'Using model: {os.path.basename(model_dir)}\n')

    kpath = load_kpath()

    for cell_label in ('uc', 'sc'):
        print(f'{"="*50}')
        print(f'Processing {cell_label.upper()}')
        print(f'{"="*50}')
        process_cell(cell_label, model_dir, kpath, params)

    print('\ncompare_bands.py done.')


if __name__ == '__main__':
    main()