File size: 4,141 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
#!/usr/bin/env python
"""
Run HPRO real-space reconstruction for all displaced configs and bands folders.

Steps for each directory:
  1. Ensures the aobasis exists (runs SIESTA in example/diamond/aobasis/ if needed)
  2. Runs HPRO calc.py in reconstruction/ using the hpro conda environment

Usage: python reconstruct.py [params.json]
"""
import glob
import json
import os
import subprocess
import sys

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 conda_run(env, cmd, cwd, conda_base, log_file=None):
    """Run a command in a conda environment."""
    activate = f"source {conda_base}/etc/profile.d/conda.sh && conda activate {env}"
    full_cmd = f"{activate} && {cmd}"
    if log_file:
        full_cmd += f" > {log_file} 2>&1"
    subprocess.run(['bash', '-c', full_cmd], cwd=cwd, check=True)


def ensure_aobasis(aobasis_dir, params):
    """Run SIESTA in aobasis/ if the HSX file is not present."""
    hsx = os.path.join(aobasis_dir, 'siesta.HSX')
    if os.path.exists(hsx):
        print(f"  aobasis already computed: {aobasis_dir}")
        return

    fdf = os.path.join(aobasis_dir, 'siesta.fdf')
    if not os.path.exists(fdf):
        print(f"  ERROR: {fdf} not found. Cannot run SIESTA.")
        print("  Provide siesta.fdf and required pseudopotentials in aobasis/")
        sys.exit(1)

    siesta_exe = params['paths']['siesta']
    np_mpi = params['execution']['mpi_np']
    print(f"  Running SIESTA for aobasis in {aobasis_dir}")
    bash_cmd = f"mpirun -np {np_mpi} {siesta_exe} < siesta.fdf > siesta.out 2>&1"
    subprocess.run(['bash', '-c', bash_cmd], cwd=aobasis_dir, check=True)


def run_hpro(recon_dir, params):
    """Run HPRO calc.py in reconstruction/ if not already done."""
    out_h5 = os.path.join(recon_dir, 'aohamiltonian', 'hamiltonians.h5')
    if os.path.exists(out_h5):
        print(f"    HPRO already done: {recon_dir}")
        return

    calc_py = os.path.join(recon_dir, 'calc.py')
    if not os.path.exists(calc_py):
        print(f"    WARNING: {calc_py} not found, skipping")
        return

    print(f"    Running HPRO in {recon_dir}")
    hpro_env = params['hpro']['conda_env']
    conda_base = params['paths']['conda_base']
    conda_run(hpro_env, 'python calc.py', recon_dir, conda_base, 'hpro.log')


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')
    data_dir = os.path.join(SCRIPT_DIR, 'data')

    if not os.path.isdir(data_dir):
        print("data/ not found – run prepare.py first")
        sys.exit(1)

    # Ensure SIESTA aobasis is available
    print("Checking aobasis...")
    ensure_aobasis(aobasis_dir, params)

    # Displaced configs
    disp_dirs = sorted(glob.glob(os.path.join(data_dir, 'disp-*')))
    print(f"\nReconstructing {len(disp_dirs)} displaced configurations...")
    for disp_dir in disp_dirs:
        label = os.path.basename(disp_dir)
        print(f"  [{label}]")
        recon_dir = os.path.join(disp_dir, 'reconstruction')
        if not os.path.exists(os.path.join(disp_dir, 'scf', 'VSC')):
            print(f"    WARNING: VSC not found, run run.py first")
            continue
        run_hpro(recon_dir, params)

    # Band structure folders
    for cell_label in ('uc', 'sc'):
        bands_dir = os.path.join(data_dir, 'bands', cell_label)
        if not os.path.isdir(bands_dir):
            continue
        print(f"\nReconstructing bands/{cell_label}...")
        recon_dir = os.path.join(bands_dir, 'reconstruction')
        if not os.path.exists(os.path.join(bands_dir, 'scf', 'VSC')):
            print(f"  WARNING: VSC not found for bands/{cell_label}, run run.py first")
            continue
        run_hpro(recon_dir, params)

    print("\nreconstruct.py done. Run compare_bands.py to plot results.")


if __name__ == '__main__':
    main()