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
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
#!/usr/bin/env julia
#=
EPC with ML/HPRO AO brackets for diamond + comparison plots.

Loads precomputed AO brackets from ml_epc.py and runs EPC using
ElectronPhonon.jl with ML/HPRO eigenvectors instead of DFT wavefunctions.
Compares results against DFT EPC from diamond.jl (out_dft/).

Prerequisites:
  1. diamond.jl (create + run + prepare + calc_ep) → displacements/out_dft/
  2. ml_epc.py (all steps) → displacements/scf_0/ao_brackets_{hpro,e3}.npz

Usage:
  cd example/diamond/3_epc
  julia diamond_ml.jl
=#
using ElectronPhonon, PythonCall, NPZ, Printf, Statistics

# ============================================================
# Paths (same model as diamond.jl)
# ============================================================
SCRIPT_DIR   = @__DIR__
path_to_calc = SCRIPT_DIR * "/"
path_to_qe   = "/home/apolyukhin/Development/q-e_tmp/"
mpi_ranks    = 8

a        = 3.567
sc_size  = [1, 1, 1]
k_mesh   = [6, 6, 6]
natoms   = 2
Ndisplace = 6 * natoms

pseudo_dir = SCRIPT_DIR * "/../pseudos/"

unitcell = Dict(
    :symbols          => pylist(["C", "C"]),
    :cell             => pylist([
        [0.0,   a/2, a/2],
        [a/2,   0.0, a/2],
        [a/2,   a/2, 0.0]
    ]),
    :scaled_positions => pylist([
        (0.0, 0.0, 0.0),
        (0.25, 0.25, 0.25)
    ]),
    :masses           => pylist([12.011, 12.011]),
)

scf_parameters = Dict(
    :format           => "espresso-in",
    :kpts             => pytuple((k_mesh[1], k_mesh[2], k_mesh[3])),
    :calculation      => "scf",
    :prefix           => "scf",
    :outdir           => "./tmp/",
    :pseudo_dir       => pseudo_dir,
    :ecutwfc          => 60,
    :conv_thr         => 1.0e-13,
    :pseudopotentials => Dict("C" => "C.upf"),
    :diagonalization  => "david",
    :mixing_mode      => "plain",
    :mixing_beta      => 0.7,
    :crystal_coordinates => true,
    :verbosity        => "high",
    :tstress          => false,
    :ibrav            => 0,
    :tprnfor          => true,
    :nbnd             => 8,
    :electron_maxstep => 1000,
    :nosym            => true,
    :noinv            => true,
)

model = create_model(
    path_to_calc   = path_to_calc,
    abs_disp       = 1e-3,
    path_to_qe     = path_to_qe,
    mpi_ranks      = mpi_ranks,
    sc_size        = sc_size,
    k_mesh         = k_mesh,
    Ndispalce      = Ndisplace,
    unitcell       = unitcell,
    scf_parameters = scf_parameters,
    use_symm       = false,
)

# Load DFT electrons/phonons (for k_list and phonons reference)
println("Loading DFT electrons and phonons...")
electrons_dft = load_electrons(model)
phonons       = load_phonons(model)

disp_dir = path_to_calc * "displacements/"
scf0_dir = disp_dir * "scf_0/"

# ============================================================
# Helper: load AO brackets from npz
# ============================================================

function load_ao_brackets(npz_file)
    data    = npzread(npz_file)
    U_raw   = data["U_list"]    # (n_dirs, nk, nk, nbands, nbands) complex128
    V_raw   = data["V_list"]
    ek_raw  = data["ek_list"]   # (nk, nbands)
    ep_raw  = data["ep_list"]   # (n_dirs, nk, nbands)
    epm_raw = data["epm_list"]

    ndisp  = size(U_raw, 1)
    nk     = size(U_raw, 2)

    U_list   = [U_raw[d, :, :, :, :]   for d in 1:ndisp]
    V_list   = [V_raw[d, :, :, :, :]   for d in 1:ndisp]
    ek_list  = [ek_raw[ik, :]           for ik in 1:nk]
    ep_list  = [[ep_raw[d, ik, :]       for ik in 1:nk] for d in 1:ndisp]
    epm_list = [[epm_raw[d, ik, :]      for ik in 1:nk] for d in 1:ndisp]

    return U_list, V_list, ek_list, ep_list, epm_list
end

# ============================================================
# Helper: run EPC for one source and save to out_{source}_ao/
# ============================================================

function run_epc_ao(source::String)
    npz_file = scf0_dir * "ao_brackets_$(source).npz"
    if !isfile(npz_file)
        println("WARNING: $(npz_file) not found — run ml_epc.py first")
        return false
    end

    println("\n" * "="^60)
    println("Running EPC with AO brackets from $(uppercase(source))")
    println("="^60)

    U_list, V_list, ek_list, ep_list, epm_list = load_ao_brackets(npz_file)

    println("  Displacements: $(length(U_list)),  k-points: $(length(ek_list))")
    println("  Gamma eigenvalues (eV): ", round.(ek_list[1], digits=4))

    nk_total   = prod(k_mesh)
    out_dir    = disp_dir * "out/"
    out_ao_dir = disp_dir * "out_$(source)_ao/"
    out_backup = disp_dir * "out_backup/"

    # Skip if output already complete
    if isdir(out_ao_dir) && length(readdir(out_ao_dir)) >= nk_total
        println("  Cached output found ($(length(readdir(out_ao_dir))) files) — skipping EPC run")
        return true
    end

    electrons_ao = Electrons(
        U_list, V_list,
        ek_list, ep_list, epm_list,
        electrons_dft.k_list,
    )

    if isdir(out_dir)
        mv(out_dir, out_backup; force=true)
    end
    mkpath(out_dir)

    println("Calculating EPC for $(nk_total) k-points...")
    for ik in 1:nk_total
        electron_phonon(model, ik, 1, electrons_ao, phonons; phonons_dfpt=false)
        if ik % 50 == 0
            println("  Done $(ik) / $(nk_total)")
        end
    end

    if isdir(out_ao_dir)
        rm(out_ao_dir; recursive=true)
    end
    mv(out_dir, out_ao_dir)
    if isdir(out_backup)
        mv(out_backup, out_dir)
    end

    println("Done! Files saved to: out_$(source)_ao/ ($(length(readdir(out_ao_dir))) files)")
    return true
end

# Run EPC for both sources
run_epc_ao("hpro")
run_epc_ao("e3")

# ============================================================
# EPC comparison: parse comparison files
# ============================================================

function parse_epc_dir(dir::String, nk::Int=216)
    g = Dict{Tuple{Int,Int,Int}, Float64}()
    for ik in 1:nk
        fn = joinpath(dir, "comparison_$(ik)_1.txt")
        isfile(fn) || continue
        open(fn) do f
            for line in eachline(f)
                cols = split(strip(line))
                length(cols) >= 8 || continue
                i  = parse(Int,   cols[1])
                j  = parse(Int,   cols[2])
                nu = parse(Int,   cols[3])
                gv = parse(Float64, cols[8])
                g[(i, j, nu)] = gv
            end
        end
    end
    return g
end

println("\n" * "="^60)
println("EPC comparison: DFT vs HPRO_AO vs E3_AO")
println("="^60)

out_dft_dir  = disp_dir * "out_dft/"
out_hpro_dir = disp_dir * "out_hpro_ao/"
out_e3_dir   = disp_dir * "out_e3_ao/"

nk     = prod(k_mesh)
nbands = 8
nmodes = 6
n_occ  = 4  # occupied bands

if !isdir(out_dft_dir)
    println("WARNING: out_dft/ not found — run diamond.jl calc_ep first")
else
    g_dft  = parse_epc_dir(out_dft_dir,  nk)
    g_hpro = isdir(out_hpro_dir) ? parse_epc_dir(out_hpro_dir, nk) : Dict()
    g_e3   = isdir(out_e3_dir)   ? parse_epc_dir(out_e3_dir,   nk) : Dict()

    println("  DFT:      $(length(g_dft)) elements")
    println("  HPRO_AO:  $(length(g_hpro)) elements")
    println("  E3_AO:    $(length(g_e3)) elements")

    # Per-mode MAE statistics
    @printf("\nPer-mode MAE (optical modes ν≥4, |g_DFT|>0.1 meV):\n")
    for nu in 4:nmodes
        errs_hpro = Float64[]
        errs_e3   = Float64[]
        for (key, gd) in g_dft
            key[3] == nu || continue
            abs(gd) > 1e-4 || continue
            if haskey(g_hpro, key)
                push!(errs_hpro, abs(g_hpro[key] - gd))
            end
            if haskey(g_e3, key)
                push!(errs_e3, abs(g_e3[key] - gd))
            end
        end
        n = length(errs_hpro)
        hpro_mae = n > 0 ? mean(errs_hpro) * 1000 : NaN
        e3_mae   = length(errs_e3) > 0 ? mean(errs_e3) * 1000 : NaN
        @printf("  Mode %d: HPRO MAE=%.2f meV  E3 MAE=%.2f meV  (N=%d)\n",
                nu, hpro_mae, e3_mae, n)
    end

    # Diagonal vs off-diagonal breakdown (optical modes)
    for (label, src_g) in [("HPRO", g_hpro), ("E3", g_e3)]
        isempty(src_g) && continue
        diag_errs    = Float64[]
        offdiag_errs = Float64[]
        vc_errs      = Float64[]

        for (key, gd) in g_dft
            key[3] >= 4 || continue
            abs(gd) > 1e-4 || continue
            haskey(src_g, key) || continue
            i, j = key[1], key[2]
            err = abs(src_g[key] - gd)
            if i == j
                push!(diag_errs, err)
            elseif (i <= n_occ) != (j <= n_occ)
                push!(vc_errs, err)
            else
                push!(offdiag_errs, err)
            end
        end

        @printf("\n  %s_AO vs DFT (optical, |g_DFT|>0.1 meV):\n", label)
        @printf("    occ-occ   diagonal  MAE = %.2f meV  (N=%d)\n",
                isempty(diag_errs)    ? NaN : mean(diag_errs)*1000,    length(diag_errs))
        @printf("    occ-occ off-diag   MAE = %.2f meV  (N=%d)\n",
                isempty(offdiag_errs) ? NaN : mean(offdiag_errs)*1000, length(offdiag_errs))
        @printf("    occ-cond/cond-occ  MAE = %.2f meV  (N=%d)\n",
                isempty(vc_errs)      ? NaN : mean(vc_errs)*1000,      length(vc_errs))

        all_errs = vcat(diag_errs, offdiag_errs, vc_errs)
        if !isempty(all_errs)
            @printf("    Overall optical   MAE = %.2f meV  (N=%d)\n",
                    mean(all_errs)*1000, length(all_errs))
        end
    end

    # ============================================================
    # Comparison plots — write Python script to tempfile and run
    # ============================================================
    println("\nGenerating comparison plots...")

    plot_path1 = SCRIPT_DIR * "/epc_comparison_ml.png"
    plot_path2 = SCRIPT_DIR * "/epc_per_kpoint_ml.png"

    plot_script = tempname() * ".py"
    write(plot_script, """
import sys, os
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

def parse_epc_dir(dir_path, nk=216):
    g = {}
    for ik in range(1, nk+1):
        fn = os.path.join(dir_path, f"comparison_{ik}_1.txt")
        if not os.path.isfile(fn):
            continue
        with open(fn) as f:
            for line in f:
                cols = line.split()
                if len(cols) < 8:
                    continue
                i, j, nu = int(cols[0]), int(cols[1]), int(cols[2])
                g[(ik, i, j, nu)] = float(cols[7])
    return g

def make_epc_plot(out_dft_dir, ml_dirs, labels, n_occ=4, nk=216, out_path="epc_comparison.png"):
    \"\"\"Scatter plot: 3 columns (occ-occ / cond-cond / occ-cond) per ML method row.\"\"\"
    g_dft = parse_epc_dir(out_dft_dir, nk)
    optical_keys = [k for k in g_dft if k[3] >= 4 and abs(g_dft[k]) > 1e-4]
    g_dft_arr = np.array([g_dft[k] for k in optical_keys]) * 1000  # meV
    is_vv = np.array([k[1] <= n_occ and k[2] <= n_occ for k in optical_keys])
    is_cc = np.array([k[1] >  n_occ and k[2] >  n_occ for k in optical_keys])
    is_vc = ~is_vv & ~is_cc
    cats = [('occ-occ', is_vv, 'C0'), ('cond-cond', is_cc, 'C1'), ('occ-cond', is_vc, 'C2')]

    nrows, ncols = len(ml_dirs), 3
    fig, axes = plt.subplots(nrows, ncols, figsize=(5*ncols, 5*nrows), squeeze=False)

    for row, (ml_dir, ml_label) in enumerate(zip(ml_dirs, labels)):
        if not os.path.isdir(ml_dir):
            continue
        g_ml = parse_epc_dir(ml_dir, nk)
        g_ml_arr = np.array([g_ml.get(k, 0.0) for k in optical_keys]) * 1000

        for col, (cat_label, mask, color) in enumerate(cats):
            ax = axes[row, col]
            if mask.sum() == 0:
                ax.set_visible(False); continue
            gd = g_dft_arr[mask]; gm = g_ml_arr[mask]
            mae = np.mean(np.abs(gm - gd))
            lim = max(abs(gd).max(), abs(gm).max()) * 1.05
            ax.scatter(gd, gm, s=4, alpha=0.3, c=color, rasterized=True)
            ax.plot([-lim, lim], [-lim, lim], 'k--', lw=0.8, alpha=0.6)
            ax.set_xlim(-lim, lim); ax.set_ylim(-lim, lim); ax.set_aspect('equal')
            ax.set_xlabel('DFT g (meV)', fontsize=9)
            ax.set_ylabel(f'{ml_label} g (meV)', fontsize=9)
            ax.set_title(f'{ml_label} — {cat_label}\\nMAE={mae:.1f} meV  N={mask.sum()}', fontsize=9)

    plt.tight_layout()
    plt.savefig(out_path, dpi=150, bbox_inches='tight')
    plt.close(fig)
    print(f'  Saved: {out_path}')


def make_per_kpoint_plot(out_dft_dir, ml_dirs, labels, n_occ=4, nk=216,
                          out_path="epc_per_kpoint.png"):
    \"\"\"Stacked bar chart: per-k-point MAE for occ-occ / cond-cond / occ-cond.\"\"\"
    g_dft = parse_epc_dir(out_dft_dir, nk)
    optical_keys = [k for k in g_dft if k[3] >= 4 and abs(g_dft[k]) > 1e-4]
    g_dft_arr = np.array([g_dft[k] for k in optical_keys]) * 1000
    is_vv = np.array([k[1] <= n_occ and k[2] <= n_occ for k in optical_keys])
    is_cc = np.array([k[1] >  n_occ and k[2] >  n_occ for k in optical_keys])
    is_vc = ~is_vv & ~is_cc
    ik_arr = np.array([k[0] for k in optical_keys])
    k_idx  = np.arange(1, nk + 1)

    fig, axes = plt.subplots(len(ml_dirs), 1,
                             figsize=(14, 4.5 * len(ml_dirs)), squeeze=False)

    for row, (ml_dir, ml_label) in enumerate(zip(ml_dirs, labels)):
        if not os.path.isdir(ml_dir):
            continue
        g_ml = parse_epc_dir(ml_dir, nk)
        g_ml_arr = np.array([g_ml.get(k, 0.0) for k in optical_keys]) * 1000

        def per_k_mae(mask):
            out = np.zeros(nk)
            for ik in k_idx:
                sel = (ik_arr == ik) & mask
                if sel.any():
                    out[ik - 1] = np.mean(np.abs(g_ml_arr[sel] - g_dft_arr[sel]))
            return out

        vv_mae = per_k_mae(is_vv)
        cc_mae = per_k_mae(is_cc)
        vc_mae = per_k_mae(is_vc)

        avg_vv = vv_mae[vv_mae > 0].mean() if vv_mae.any() else 0.0
        avg_cc = cc_mae[cc_mae > 0].mean() if cc_mae.any() else 0.0
        avg_vc = vc_mae[vc_mae > 0].mean() if vc_mae.any() else 0.0

        ax = axes[row, 0]
        ax.bar(k_idx, vv_mae, color='C0', label=f'val-val (avg={avg_vv:.1f})', width=1.0)
        ax.bar(k_idx, cc_mae, bottom=vv_mae, color='C1',
               label=f'cond-cond (avg={avg_cc:.1f})', width=1.0)
        ax.bar(k_idx, vc_mae, bottom=vv_mae + cc_mae, color='C2',
               label=f'val-cond (avg={avg_vc:.1f})', width=1.0)
        ax.set_xlabel('k-point index', fontsize=10)
        ax.set_ylabel('MAE (meV)', fontsize=10)
        ax.set_title(f'{ml_label}: Per k-point EPC MAE', fontsize=11)
        ax.legend(fontsize=9, loc='upper right')

    plt.tight_layout()
    plt.savefig(out_path, dpi=150, bbox_inches='tight')
    plt.close(fig)
    print(f'  Saved: {out_path}')

if __name__ == "__main__":
    out_dft_dir, out_hpro_dir, out_e3_dir, path1, path2 = sys.argv[1:6]
    make_epc_plot(out_dft_dir, [out_hpro_dir, out_e3_dir], ['HPRO_AO', 'E3_AO'], out_path=path1)
    make_per_kpoint_plot(out_dft_dir, [out_hpro_dir, out_e3_dir], ['HPRO_AO', 'E3_AO'], out_path=path2)
""")
    try
        # Use epc_ml conda env python; fall back to Sys.which (honours PATH from conda run)
        python_exe = let p = expanduser("~/anaconda3/envs/epc_ml/bin/python")
            isfile(p) ? p : something(Sys.which("python"), "python")
        end
        run(`$python_exe $plot_script $out_dft_dir $out_hpro_dir $out_e3_dir $plot_path1 $plot_path2`)
    finally
        rm(plot_script; force=true)
    end

    println("\ndiamond_ml.jl done.")
    println("  epc_comparison_ml.png  — scatter: DFT vs HPRO_AO vs E3_AO")
    println("  epc_error_dist_ml.png  — error histograms per band category")
end