| |
| |
| 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 |
|
|
| |
| |
| |
| 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, |
| ) |
|
|
| |
| 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/" |
|
|
| |
| |
| |
|
|
| function load_ao_brackets(npz_file) |
| data = npzread(npz_file) |
| U_raw = data["U_list"] |
| V_raw = data["V_list"] |
| ek_raw = data["ek_list"] |
| ep_raw = data["ep_list"] |
| 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 |
|
|
| |
| |
| |
|
|
| 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/" |
|
|
| |
| 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_ao("hpro") |
| run_epc_ao("e3") |
|
|
| |
| |
| |
|
|
| 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 |
|
|
| 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") |
|
|
| |
| @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 |
|
|
| |
| 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 |
|
|
| |
| |
| |
| 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 |
| |
| 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 |
|
|