Add files using upload-large-folder tool
Browse files- 2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/preprocess/__init__.py +4 -0
- 2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/preprocess/__pycache__/__init__.cpython-312.pyc +0 -0
- 2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/preprocess/__pycache__/abacus_get_data.cpython-312.pyc +0 -0
- 2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/preprocess/__pycache__/get_rc.cpython-312.pyc +0 -0
- 2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/preprocess/__pycache__/openmx_parse.cpython-312.pyc +0 -0
- 2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/preprocess/abacus_get_data.py +340 -0
- 2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/preprocess/aims_get_data.jl +477 -0
- 2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/preprocess/get_rc.py +165 -0
- 2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/preprocess/openmx_get_data.jl +471 -0
- 2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/preprocess/openmx_parse.py +425 -0
- 2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/preprocess/periodic_table.json +0 -0
- 2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/preprocess/preprocess_default.ini +20 -0
- 2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/preprocess/siesta_get_data.py +336 -0
- 2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/scripts/__init__.py +0 -0
- 2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/scripts/__pycache__/__init__.cpython-312.pyc +0 -0
- 2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/scripts/__pycache__/preprocess.cpython-312.pyc +0 -0
- 2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/scripts/__pycache__/train.cpython-312.pyc +0 -0
- 2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/scripts/inference.py +157 -0
- 2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/scripts/preprocess.py +199 -0
- 2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/scripts/train.py +23 -0
2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/preprocess/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .openmx_parse import OijLoad, GetEEiEij, openmx_parse_overlap
|
| 2 |
+
from .get_rc import get_rc
|
| 3 |
+
from .abacus_get_data import abacus_parse
|
| 4 |
+
from .siesta_get_data import siesta_parse
|
2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/preprocess/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (394 Bytes). View file
|
|
|
2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/preprocess/__pycache__/abacus_get_data.cpython-312.pyc
ADDED
|
Binary file (23 kB). View file
|
|
|
2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/preprocess/__pycache__/get_rc.cpython-312.pyc
ADDED
|
Binary file (11.2 kB). View file
|
|
|
2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/preprocess/__pycache__/openmx_parse.cpython-312.pyc
ADDED
|
Binary file (31.5 kB). View file
|
|
|
2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/preprocess/abacus_get_data.py
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 4 |
+
# To use this script, please add 'out_mat_hs2 1' in ABACUS INPUT File
|
| 5 |
+
# Current version is capable of coping with f-orbitals
|
| 6 |
+
# 20220717: Read structure from running_scf.log
|
| 7 |
+
# 20220919: The suffix of the output sub-directories (OUT.suffix) can be set by ["basic"]["abacus_suffix"] keyword in preprocess.ini
|
| 8 |
+
# 20220920: Supporting cartesian coordinates in the log file
|
| 9 |
+
# 20231228: Supporting ABACUS v3.4
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
import json
|
| 14 |
+
import re
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
from scipy.sparse import csr_matrix
|
| 18 |
+
from scipy.linalg import block_diag
|
| 19 |
+
import argparse
|
| 20 |
+
import h5py
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
Bohr2Ang = 0.529177249
|
| 24 |
+
periodic_table = {'Ac': 89, 'Ag': 47, 'Al': 13, 'Am': 95, 'Ar': 18, 'As': 33, 'At': 85, 'Au': 79, 'B': 5, 'Ba': 56,
|
| 25 |
+
'Be': 4, 'Bi': 83, 'Bk': 97, 'Br': 35, 'C': 6, 'Ca': 20, 'Cd': 48, 'Ce': 58, 'Cf': 98, 'Cl': 17,
|
| 26 |
+
'Cm': 96, 'Co': 27, 'Cr': 24, 'Cs': 55, 'Cu': 29, 'Dy': 66, 'Er': 68, 'Es': 99, 'Eu': 63, 'F': 9,
|
| 27 |
+
'Fe': 26, 'Fm': 100, 'Fr': 87, 'Ga': 31, 'Gd': 64, 'Ge': 32, 'H': 1, 'He': 2, 'Hf': 72, 'Hg': 80,
|
| 28 |
+
'Ho': 67, 'I': 53, 'In': 49, 'Ir': 77, 'K': 19, 'Kr': 36, 'La': 57, 'Li': 3, 'Lr': 103, 'Lu': 71,
|
| 29 |
+
'Md': 101, 'Mg': 12, 'Mn': 25, 'Mo': 42, 'N': 7, 'Na': 11, 'Nb': 41, 'Nd': 60, 'Ne': 10, 'Ni': 28,
|
| 30 |
+
'No': 102, 'Np': 93, 'O': 8, 'Os': 76, 'P': 15, 'Pa': 91, 'Pb': 82, 'Pd': 46, 'Pm': 61, 'Po': 84,
|
| 31 |
+
'Pr': 59, 'Pt': 78, 'Pu': 94, 'Ra': 88, 'Rb': 37, 'Re': 75, 'Rh': 45, 'Rn': 86, 'Ru': 44, 'S': 16,
|
| 32 |
+
'Sb': 51, 'Sc': 21, 'Se': 34, 'Si': 14, 'Sm': 62, 'Sn': 50, 'Sr': 38, 'Ta': 73, 'Tb': 65, 'Tc': 43,
|
| 33 |
+
'Te': 52, 'Th': 90, 'Ti': 22, 'Tl': 81, 'Tm': 69, 'U': 92, 'V': 23, 'W': 74, 'Xe': 54, 'Y': 39,
|
| 34 |
+
'Yb': 70, 'Zn': 30, 'Zr': 40, 'Rf': 104, 'Db': 105, 'Sg': 106, 'Bh': 107, 'Hs': 108, 'Mt': 109,
|
| 35 |
+
'Ds': 110, 'Rg': 111, 'Cn': 112, 'Nh': 113, 'Fl': 114, 'Mc': 115, 'Lv': 116, 'Ts': 117, 'Og': 118}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class OrbAbacus2DeepH:
|
| 39 |
+
def __init__(self):
|
| 40 |
+
self.Us_abacus2deeph = {}
|
| 41 |
+
self.Us_abacus2deeph[0] = np.eye(1)
|
| 42 |
+
self.Us_abacus2deeph[1] = np.eye(3)[[1, 2, 0]]
|
| 43 |
+
self.Us_abacus2deeph[2] = np.eye(5)[[0, 3, 4, 1, 2]]
|
| 44 |
+
self.Us_abacus2deeph[3] = np.eye(7)[[0, 1, 2, 3, 4, 5, 6]]
|
| 45 |
+
|
| 46 |
+
minus_dict = {
|
| 47 |
+
1: [0, 1],
|
| 48 |
+
2: [3, 4],
|
| 49 |
+
3: [1, 2, 5, 6],
|
| 50 |
+
}
|
| 51 |
+
for k, v in minus_dict.items():
|
| 52 |
+
self.Us_abacus2deeph[k][v] *= -1
|
| 53 |
+
|
| 54 |
+
def get_U(self, l):
|
| 55 |
+
if l > 3:
|
| 56 |
+
raise NotImplementedError("Only support l = s, p, d, f")
|
| 57 |
+
return self.Us_abacus2deeph[l]
|
| 58 |
+
|
| 59 |
+
def transform(self, mat, l_lefts, l_rights):
|
| 60 |
+
block_lefts = block_diag(*[self.get_U(l_left) for l_left in l_lefts])
|
| 61 |
+
block_rights = block_diag(*[self.get_U(l_right) for l_right in l_rights])
|
| 62 |
+
return block_lefts @ mat @ block_rights.T
|
| 63 |
+
|
| 64 |
+
def abacus_parse(input_path, output_path, data_name, only_S=False, get_r=False):
|
| 65 |
+
input_path = os.path.abspath(input_path)
|
| 66 |
+
output_path = os.path.abspath(output_path)
|
| 67 |
+
os.makedirs(output_path, exist_ok=True)
|
| 68 |
+
|
| 69 |
+
def find_target_line(f, target):
|
| 70 |
+
line = f.readline()
|
| 71 |
+
while line:
|
| 72 |
+
if target in line:
|
| 73 |
+
return line
|
| 74 |
+
line = f.readline()
|
| 75 |
+
return None
|
| 76 |
+
if only_S:
|
| 77 |
+
log_file_name = "running_get_S.log"
|
| 78 |
+
else:
|
| 79 |
+
log_file_name = "running_scf.log"
|
| 80 |
+
with open(os.path.join(input_path, data_name, log_file_name), 'r') as f:
|
| 81 |
+
f.readline()
|
| 82 |
+
line = f.readline()
|
| 83 |
+
# assert "WELCOME TO ABACUS" in line
|
| 84 |
+
assert find_target_line(f, "READING UNITCELL INFORMATION") is not None, 'Cannot find "READING UNITCELL INFORMATION" in log file'
|
| 85 |
+
num_atom_type = int(f.readline().split()[-1])
|
| 86 |
+
|
| 87 |
+
assert find_target_line(f, "lattice constant (Bohr)") is not None
|
| 88 |
+
lattice_constant = float(f.readline().split()[-1]) # unit is Angstrom
|
| 89 |
+
|
| 90 |
+
site_norbits_dict = {}
|
| 91 |
+
orbital_types_dict = {}
|
| 92 |
+
for index_type in range(num_atom_type):
|
| 93 |
+
tmp = find_target_line(f, "READING ATOM TYPE")
|
| 94 |
+
assert tmp is not None, 'Cannot find "ATOM TYPE" in log file'
|
| 95 |
+
assert tmp.split()[-1] == str(index_type + 1)
|
| 96 |
+
if tmp is None:
|
| 97 |
+
raise Exception(f"Cannot find ATOM {index_type} in {log_file_name}")
|
| 98 |
+
|
| 99 |
+
line = f.readline()
|
| 100 |
+
assert "atom label =" in line
|
| 101 |
+
atom_label = line.split()[-1]
|
| 102 |
+
assert atom_label in periodic_table, "Atom label should be in periodic table"
|
| 103 |
+
atom_type = periodic_table[atom_label]
|
| 104 |
+
|
| 105 |
+
current_site_norbits = 0
|
| 106 |
+
current_orbital_types = []
|
| 107 |
+
while True:
|
| 108 |
+
line = f.readline()
|
| 109 |
+
if "number of zeta" in line:
|
| 110 |
+
tmp = line.split()
|
| 111 |
+
L = int(tmp[0][2:-1])
|
| 112 |
+
num_L = int(tmp[-1])
|
| 113 |
+
current_site_norbits += (2 * L + 1) * num_L
|
| 114 |
+
current_orbital_types.extend([L] * num_L)
|
| 115 |
+
else:
|
| 116 |
+
break
|
| 117 |
+
site_norbits_dict[atom_type] = current_site_norbits
|
| 118 |
+
orbital_types_dict[atom_type] = current_orbital_types
|
| 119 |
+
|
| 120 |
+
line = find_target_line(f, "TOTAL ATOM NUMBER")
|
| 121 |
+
assert line is not None, 'Cannot find "TOTAL ATOM NUMBER" in log file'
|
| 122 |
+
nsites = int(line.split()[-1])
|
| 123 |
+
|
| 124 |
+
line = find_target_line(f, " COORDINATES")
|
| 125 |
+
assert line is not None, 'Cannot find "DIRECT COORDINATES" or "CARTESIAN COORDINATES" in log file'
|
| 126 |
+
if "DIRECT" in line:
|
| 127 |
+
coords_type = "direct"
|
| 128 |
+
elif "CARTESIAN" in line:
|
| 129 |
+
coords_type = "cartesian"
|
| 130 |
+
else:
|
| 131 |
+
raise ValueError('Cannot find "DIRECT COORDINATES" or "CARTESIAN COORDINATES" in log file')
|
| 132 |
+
|
| 133 |
+
assert "atom" in f.readline()
|
| 134 |
+
frac_coords = np.zeros((nsites, 3))
|
| 135 |
+
site_norbits = np.zeros(nsites, dtype=int)
|
| 136 |
+
element = np.zeros(nsites, dtype=int)
|
| 137 |
+
for index_site in range(nsites):
|
| 138 |
+
line = f.readline()
|
| 139 |
+
tmp = line.split()
|
| 140 |
+
assert "tau" in tmp[0]
|
| 141 |
+
atom_label = ''.join(re.findall(r'[A-Za-z]', tmp[0][5:]))
|
| 142 |
+
assert atom_label in periodic_table, "Atom label should be in periodic table"
|
| 143 |
+
element[index_site] = periodic_table[atom_label]
|
| 144 |
+
site_norbits[index_site] = site_norbits_dict[element[index_site]]
|
| 145 |
+
frac_coords[index_site, :] = np.array(tmp[1:4])
|
| 146 |
+
norbits = int(np.sum(site_norbits))
|
| 147 |
+
site_norbits_cumsum = np.cumsum(site_norbits)
|
| 148 |
+
|
| 149 |
+
assert find_target_line(f, "Lattice vectors: (Cartesian coordinate: in unit of a_0)") is not None
|
| 150 |
+
lattice = np.zeros((3, 3))
|
| 151 |
+
for index_lat in range(3):
|
| 152 |
+
lattice[index_lat, :] = np.array(f.readline().split())
|
| 153 |
+
if coords_type == "cartesian":
|
| 154 |
+
frac_coords = frac_coords @ np.matrix(lattice).I
|
| 155 |
+
lattice = lattice * lattice_constant
|
| 156 |
+
if only_S:
|
| 157 |
+
spinful = False
|
| 158 |
+
else:
|
| 159 |
+
line = find_target_line(f, "NSPIN")
|
| 160 |
+
assert line is not None, 'Cannot find "NSPIN" in log file'
|
| 161 |
+
if "NSPIN == 1" in line:
|
| 162 |
+
spinful = False
|
| 163 |
+
elif "NSPIN == 4" in line:
|
| 164 |
+
spinful = True
|
| 165 |
+
else:
|
| 166 |
+
raise ValueError(f'{line} is not supported')
|
| 167 |
+
if only_S:
|
| 168 |
+
fermi_level = 0.0
|
| 169 |
+
else:
|
| 170 |
+
with open(os.path.join(input_path, data_name, log_file_name), 'r') as f:
|
| 171 |
+
line = find_target_line(f, "EFERMI")
|
| 172 |
+
assert line is not None, 'Cannot find "EFERMI" in log file'
|
| 173 |
+
assert "eV" in line
|
| 174 |
+
fermi_level = float(line.split()[2])
|
| 175 |
+
assert find_target_line(f, "EFERMI") is None, "There is more than one EFERMI in log file"
|
| 176 |
+
|
| 177 |
+
np.savetxt(os.path.join(output_path, "lat.dat"), np.transpose(lattice))
|
| 178 |
+
np.savetxt(os.path.join(output_path, "rlat.dat"), np.linalg.inv(lattice) * 2 * np.pi)
|
| 179 |
+
cart_coords = frac_coords @ lattice
|
| 180 |
+
np.savetxt(os.path.join(output_path, "site_positions.dat").format(output_path), np.transpose(cart_coords))
|
| 181 |
+
np.savetxt(os.path.join(output_path, "element.dat"), element, fmt='%d')
|
| 182 |
+
info = {'nsites' : nsites, 'isorthogonal': False, 'isspinful': spinful, 'norbits': norbits, 'fermi_level': fermi_level}
|
| 183 |
+
with open('{}/info.json'.format(output_path), 'w') as info_f:
|
| 184 |
+
json.dump(info, info_f)
|
| 185 |
+
with open(os.path.join(output_path, "orbital_types.dat"), 'w') as f:
|
| 186 |
+
for atomic_number in element:
|
| 187 |
+
for index_l, l in enumerate(orbital_types_dict[atomic_number]):
|
| 188 |
+
if index_l == 0:
|
| 189 |
+
f.write(str(l))
|
| 190 |
+
else:
|
| 191 |
+
f.write(f" {l}")
|
| 192 |
+
f.write('\n')
|
| 193 |
+
|
| 194 |
+
U_orbital = OrbAbacus2DeepH()
|
| 195 |
+
def parse_matrix(matrix_path, factor, spinful=False):
|
| 196 |
+
matrix_dict = dict()
|
| 197 |
+
with open(matrix_path, 'r') as f:
|
| 198 |
+
line = f.readline() # read "Matrix Dimension of ..."
|
| 199 |
+
if not "Matrix Dimension of" in line:
|
| 200 |
+
line = f.readline() # ABACUS >= 3.0
|
| 201 |
+
assert "Matrix Dimension of" in line
|
| 202 |
+
f.readline() # read "Matrix number of ..."
|
| 203 |
+
norbits = int(line.split()[-1])
|
| 204 |
+
for line in f:
|
| 205 |
+
line1 = line.split()
|
| 206 |
+
if len(line1) == 0:
|
| 207 |
+
break
|
| 208 |
+
num_element = int(line1[3])
|
| 209 |
+
if num_element != 0:
|
| 210 |
+
R_cur = np.array(line1[:3]).astype(int)
|
| 211 |
+
line2 = f.readline().split()
|
| 212 |
+
line3 = f.readline().split()
|
| 213 |
+
line4 = f.readline().split()
|
| 214 |
+
if not spinful:
|
| 215 |
+
hamiltonian_cur = csr_matrix((np.array(line2).astype(float), np.array(line3).astype(int),
|
| 216 |
+
np.array(line4).astype(int)), shape=(norbits, norbits)).toarray()
|
| 217 |
+
else:
|
| 218 |
+
line2 = np.char.replace(line2, '(', '')
|
| 219 |
+
line2 = np.char.replace(line2, ')', 'j')
|
| 220 |
+
line2 = np.char.replace(line2, ',', '+')
|
| 221 |
+
line2 = np.char.replace(line2, '+-', '-')
|
| 222 |
+
hamiltonian_cur = csr_matrix((np.array(line2).astype(np.complex128), np.array(line3).astype(int),
|
| 223 |
+
np.array(line4).astype(int)), shape=(norbits, norbits)).toarray()
|
| 224 |
+
for index_site_i in range(nsites):
|
| 225 |
+
for index_site_j in range(nsites):
|
| 226 |
+
key_str = f"[{R_cur[0]}, {R_cur[1]}, {R_cur[2]}, {index_site_i + 1}, {index_site_j + 1}]"
|
| 227 |
+
mat = hamiltonian_cur[(site_norbits_cumsum[index_site_i]
|
| 228 |
+
- site_norbits[index_site_i]) * (1 + spinful):
|
| 229 |
+
site_norbits_cumsum[index_site_i] * (1 + spinful),
|
| 230 |
+
(site_norbits_cumsum[index_site_j] - site_norbits[index_site_j]) * (1 + spinful):
|
| 231 |
+
site_norbits_cumsum[index_site_j] * (1 + spinful)]
|
| 232 |
+
if abs(mat).max() < 1e-8:
|
| 233 |
+
continue
|
| 234 |
+
if not spinful:
|
| 235 |
+
mat = U_orbital.transform(mat, orbital_types_dict[element[index_site_i]],
|
| 236 |
+
orbital_types_dict[element[index_site_j]])
|
| 237 |
+
else:
|
| 238 |
+
mat = mat.reshape((site_norbits[index_site_i], 2, site_norbits[index_site_j], 2))
|
| 239 |
+
mat = mat.transpose((1, 0, 3, 2)).reshape((2 * site_norbits[index_site_i],
|
| 240 |
+
2 * site_norbits[index_site_j]))
|
| 241 |
+
mat = U_orbital.transform(mat, orbital_types_dict[element[index_site_i]] * 2,
|
| 242 |
+
orbital_types_dict[element[index_site_j]] * 2)
|
| 243 |
+
matrix_dict[key_str] = mat * factor
|
| 244 |
+
return matrix_dict, norbits
|
| 245 |
+
|
| 246 |
+
if only_S:
|
| 247 |
+
overlap_dict, tmp = parse_matrix(os.path.join(input_path, "SR.csr"), 1)
|
| 248 |
+
assert tmp == norbits
|
| 249 |
+
else:
|
| 250 |
+
hamiltonian_dict, tmp = parse_matrix(
|
| 251 |
+
os.path.join(input_path, data_name, "data-HR-sparse_SPIN0.csr"), 13.605698, # Ryd2eV
|
| 252 |
+
spinful=spinful)
|
| 253 |
+
assert tmp == norbits * (1 + spinful)
|
| 254 |
+
overlap_dict, tmp = parse_matrix(os.path.join(input_path, data_name, "data-SR-sparse_SPIN0.csr"), 1,
|
| 255 |
+
spinful=spinful)
|
| 256 |
+
assert tmp == norbits * (1 + spinful)
|
| 257 |
+
if spinful:
|
| 258 |
+
overlap_dict_spinless = {}
|
| 259 |
+
for k, v in overlap_dict.items():
|
| 260 |
+
overlap_dict_spinless[k] = v[:v.shape[0] // 2, :v.shape[1] // 2].real
|
| 261 |
+
overlap_dict_spinless, overlap_dict = overlap_dict, overlap_dict_spinless
|
| 262 |
+
|
| 263 |
+
if not only_S:
|
| 264 |
+
with h5py.File(os.path.join(output_path, "hamiltonians.h5"), 'w') as fid:
|
| 265 |
+
for key_str, value in hamiltonian_dict.items():
|
| 266 |
+
fid[key_str] = value
|
| 267 |
+
with h5py.File(os.path.join(output_path, "overlaps.h5"), 'w') as fid:
|
| 268 |
+
for key_str, value in overlap_dict.items():
|
| 269 |
+
fid[key_str] = value
|
| 270 |
+
if get_r:
|
| 271 |
+
def parse_r_matrix(matrix_path, factor):
|
| 272 |
+
matrix_dict = dict()
|
| 273 |
+
with open(matrix_path, 'r') as f:
|
| 274 |
+
line = f.readline();
|
| 275 |
+
norbits = int(line.split()[-1])
|
| 276 |
+
for line in f:
|
| 277 |
+
line1 = line.split()
|
| 278 |
+
if len(line1) == 0:
|
| 279 |
+
break
|
| 280 |
+
assert len(line1) > 3
|
| 281 |
+
R_cur = np.array(line1[:3]).astype(int)
|
| 282 |
+
mat_cur = np.zeros((3, norbits * norbits))
|
| 283 |
+
for line_index in range(norbits * norbits):
|
| 284 |
+
line_mat = f.readline().split()
|
| 285 |
+
assert len(line_mat) == 3
|
| 286 |
+
mat_cur[:, line_index] = np.array(line_mat)
|
| 287 |
+
mat_cur = mat_cur.reshape((3, norbits, norbits))
|
| 288 |
+
|
| 289 |
+
for index_site_i in range(nsites):
|
| 290 |
+
for index_site_j in range(nsites):
|
| 291 |
+
for direction in range(3):
|
| 292 |
+
key_str = f"[{R_cur[0]}, {R_cur[1]}, {R_cur[2]}, {index_site_i + 1}, {index_site_j + 1}, {direction + 1}]"
|
| 293 |
+
mat = mat_cur[direction, site_norbits_cumsum[index_site_i]
|
| 294 |
+
- site_norbits[index_site_i]:site_norbits_cumsum[index_site_i],
|
| 295 |
+
site_norbits_cumsum[index_site_j]
|
| 296 |
+
- site_norbits[index_site_j]:site_norbits_cumsum[index_site_j]]
|
| 297 |
+
if abs(mat).max() < 1e-8:
|
| 298 |
+
continue
|
| 299 |
+
mat = U_orbital.transform(mat, orbital_types_dict[element[index_site_i]],
|
| 300 |
+
orbital_types_dict[element[index_site_j]])
|
| 301 |
+
matrix_dict[key_str] = mat * factor
|
| 302 |
+
return matrix_dict, norbits
|
| 303 |
+
position_dict, tmp = parse_r_matrix(os.path.join(input_path, data_name, "data-rR-tr_SPIN1"), 0.529177249) # Bohr2Ang
|
| 304 |
+
assert tmp == norbits
|
| 305 |
+
|
| 306 |
+
with h5py.File(os.path.join(output_path, "positions.h5"), 'w') as fid:
|
| 307 |
+
for key_str, value in position_dict.items():
|
| 308 |
+
fid[key_str] = value
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
if __name__ == '__main__':
|
| 312 |
+
parser = argparse.ArgumentParser(description='Predict Hamiltonian')
|
| 313 |
+
parser.add_argument(
|
| 314 |
+
'-i','--input_dir', type=str, default='./',
|
| 315 |
+
help='path of output subdirectory'
|
| 316 |
+
)
|
| 317 |
+
parser.add_argument(
|
| 318 |
+
'-o','--output_dir', type=str, default='./',
|
| 319 |
+
help='path of output .h5 and .dat'
|
| 320 |
+
)
|
| 321 |
+
parser.add_argument(
|
| 322 |
+
'-a','--abacus_suffix', type=str, default='ABACUS',
|
| 323 |
+
help='suffix of output subdirectory'
|
| 324 |
+
)
|
| 325 |
+
parser.add_argument(
|
| 326 |
+
'-S','--only_S', type=int, default=0
|
| 327 |
+
)
|
| 328 |
+
parser.add_argument(
|
| 329 |
+
'-g','--get_r', type=int, default=0
|
| 330 |
+
)
|
| 331 |
+
args = parser.parse_args()
|
| 332 |
+
|
| 333 |
+
input_path = args.input_dir
|
| 334 |
+
output_path = args.output_dir
|
| 335 |
+
data_name = "OUT." + args.abacus_suffix
|
| 336 |
+
only_S = bool(args.only_S)
|
| 337 |
+
get_r = bool(args.get_r)
|
| 338 |
+
print("only_S: {}".format(only_S))
|
| 339 |
+
print("get_r: {}".format(get_r))
|
| 340 |
+
abacus_parse(input_path, output_path, data_name, only_S, get_r)
|
2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/preprocess/aims_get_data.jl
ADDED
|
@@ -0,0 +1,477 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
using JSON
|
| 2 |
+
using HDF5
|
| 3 |
+
using LinearAlgebra
|
| 4 |
+
using DelimitedFiles
|
| 5 |
+
using StaticArrays
|
| 6 |
+
using ArgParse
|
| 7 |
+
|
| 8 |
+
function parse_commandline()
|
| 9 |
+
s = ArgParseSettings()
|
| 10 |
+
@add_arg_table! s begin
|
| 11 |
+
"--input_dir", "-i"
|
| 12 |
+
help = "NoTB.dat, basis-indices.out, geometry.in"
|
| 13 |
+
arg_type = String
|
| 14 |
+
default = "./"
|
| 15 |
+
"--output_dir", "-o"
|
| 16 |
+
help = ""
|
| 17 |
+
arg_type = String
|
| 18 |
+
default = "./output"
|
| 19 |
+
"--save_overlap", "-s"
|
| 20 |
+
help = ""
|
| 21 |
+
arg_type = Bool
|
| 22 |
+
default = false
|
| 23 |
+
"--save_position", "-p"
|
| 24 |
+
help = ""
|
| 25 |
+
arg_type = Bool
|
| 26 |
+
default = false
|
| 27 |
+
end
|
| 28 |
+
return parse_args(s)
|
| 29 |
+
end
|
| 30 |
+
parsed_args = parse_commandline()
|
| 31 |
+
|
| 32 |
+
input_dir = abspath(parsed_args["input_dir"])
|
| 33 |
+
output_dir = abspath(parsed_args["output_dir"])
|
| 34 |
+
|
| 35 |
+
@assert isfile(joinpath(input_dir, "NoTB.dat"))
|
| 36 |
+
@assert isfile(joinpath(input_dir, "basis-indices.out"))
|
| 37 |
+
@assert isfile(joinpath(input_dir, "geometry.in"))
|
| 38 |
+
|
| 39 |
+
# @info string("get data from: ", input_dir)
|
| 40 |
+
periodic_table = JSON.parsefile(joinpath(@__DIR__, "periodic_table.json"))
|
| 41 |
+
mkpath(output_dir)
|
| 42 |
+
|
| 43 |
+
# The function parse_openmx below is come from "https://github.com/HopTB/HopTB.jl"
|
| 44 |
+
f = open(joinpath(input_dir, "NoTB.dat"))
|
| 45 |
+
# number of basis
|
| 46 |
+
@assert occursin("n_basis", readline(f)) # start
|
| 47 |
+
norbits = parse(Int64, readline(f))
|
| 48 |
+
@assert occursin("end", readline(f)) # end
|
| 49 |
+
@assert occursin("n_ham", readline(f)) # start
|
| 50 |
+
nhams = parse(Int64, readline(f))
|
| 51 |
+
@assert occursin("end", readline(f)) # end
|
| 52 |
+
@assert occursin("n_cell", readline(f)) # start
|
| 53 |
+
ncells = parse(Int64, readline(f))
|
| 54 |
+
@assert occursin("end", readline(f)) # end
|
| 55 |
+
# lattice vector
|
| 56 |
+
@assert occursin("lattice_vector", readline(f)) # start
|
| 57 |
+
lat = Matrix{Float64}(I, 3, 3)
|
| 58 |
+
for i in 1:3
|
| 59 |
+
lat[:, i] = map(x->parse(Float64, x), split(readline(f)))
|
| 60 |
+
end
|
| 61 |
+
@assert occursin("end", readline(f)) # end
|
| 62 |
+
# hamiltonian
|
| 63 |
+
@assert occursin("hamiltonian", readline(f)) # start
|
| 64 |
+
hamiltonian = zeros(nhams)
|
| 65 |
+
i = 1
|
| 66 |
+
while true
|
| 67 |
+
global i
|
| 68 |
+
@assert !eof(f)
|
| 69 |
+
ln = split(readline(f))
|
| 70 |
+
if occursin("end", ln[1]) break end
|
| 71 |
+
hamiltonian[i:i + length(ln) - 1] = map(x->parse(Float64, x), ln)
|
| 72 |
+
i += length(ln)
|
| 73 |
+
end
|
| 74 |
+
# overlaps
|
| 75 |
+
@assert occursin("overlap", readline(f)) # start
|
| 76 |
+
overlaps = zeros(nhams)
|
| 77 |
+
i = 1
|
| 78 |
+
while true
|
| 79 |
+
global i
|
| 80 |
+
@assert !eof(f)
|
| 81 |
+
ln = split(readline(f))
|
| 82 |
+
if occursin("end", ln[1]) break end
|
| 83 |
+
overlaps[i:i + length(ln) - 1] = map(x->parse(Float64, x), ln)
|
| 84 |
+
i += length(ln)
|
| 85 |
+
end
|
| 86 |
+
# index hamiltonian
|
| 87 |
+
@assert occursin("index_hamiltonian", readline(f)) # start
|
| 88 |
+
indexhamiltonian = zeros(Int64, ncells * norbits, 4)
|
| 89 |
+
i = 1
|
| 90 |
+
while true
|
| 91 |
+
global i
|
| 92 |
+
@assert !eof(f)
|
| 93 |
+
ln = split(readline(f))
|
| 94 |
+
if occursin("end", ln[1]) break end
|
| 95 |
+
indexhamiltonian[i, :] = map(x->parse(Int64, x), ln)
|
| 96 |
+
i += 1
|
| 97 |
+
end
|
| 98 |
+
# cell index
|
| 99 |
+
@assert occursin("cell_index", readline(f)) # start
|
| 100 |
+
cellindex = zeros(Int64, ncells, 3)
|
| 101 |
+
i = 1
|
| 102 |
+
while true
|
| 103 |
+
global i
|
| 104 |
+
@assert !eof(f)
|
| 105 |
+
ln = split(readline(f))
|
| 106 |
+
if occursin("end", ln[1]) break end
|
| 107 |
+
if i <= ncells
|
| 108 |
+
cellindex[i, :] = map(x->parse(Int64, x), ln)
|
| 109 |
+
end
|
| 110 |
+
i += 1
|
| 111 |
+
end
|
| 112 |
+
# column index hamiltonian
|
| 113 |
+
@assert occursin("column_index_hamiltonian", readline(f)) # start
|
| 114 |
+
columnindexhamiltonian = zeros(Int64, nhams)
|
| 115 |
+
i = 1
|
| 116 |
+
while true
|
| 117 |
+
global i
|
| 118 |
+
@assert !eof(f)
|
| 119 |
+
ln = split(readline(f))
|
| 120 |
+
if occursin("end", ln[1]) break end
|
| 121 |
+
columnindexhamiltonian[i:i + length(ln) - 1] = map(x->parse(Int64, x), ln)
|
| 122 |
+
i += length(ln)
|
| 123 |
+
end
|
| 124 |
+
# positions
|
| 125 |
+
positions = zeros(nhams, 3)
|
| 126 |
+
for dir in 1:3
|
| 127 |
+
positionsdir = zeros(nhams)
|
| 128 |
+
@assert occursin("position", readline(f)) # start
|
| 129 |
+
readline(f) # skip direction
|
| 130 |
+
i = 1
|
| 131 |
+
while true
|
| 132 |
+
@assert !eof(f)
|
| 133 |
+
ln = split(readline(f))
|
| 134 |
+
if occursin("end", ln[1]) break end
|
| 135 |
+
positionsdir[i:i + length(ln) - 1] = map(x->parse(Float64, x), ln)
|
| 136 |
+
i += length(ln)
|
| 137 |
+
end
|
| 138 |
+
positions[:, dir] = positionsdir
|
| 139 |
+
end
|
| 140 |
+
if !eof(f)
|
| 141 |
+
spinful = true
|
| 142 |
+
soc_matrix = zeros(nhams, 3)
|
| 143 |
+
for dir in 1:3
|
| 144 |
+
socdir = zeros(nhams)
|
| 145 |
+
@assert occursin("soc_matrix", readline(f)) # start
|
| 146 |
+
readline(f) # skip direction
|
| 147 |
+
i = 1
|
| 148 |
+
while true
|
| 149 |
+
@assert !eof(f)
|
| 150 |
+
ln = split(readline(f))
|
| 151 |
+
if occursin("end", ln[1]) break end
|
| 152 |
+
socdir[i:i + length(ln) - 1] = map(x->parse(Float64, x), ln)
|
| 153 |
+
i += length(ln)
|
| 154 |
+
end
|
| 155 |
+
soc_matrix[:, dir] = socdir
|
| 156 |
+
end
|
| 157 |
+
else
|
| 158 |
+
spinful = false
|
| 159 |
+
end
|
| 160 |
+
close(f)
|
| 161 |
+
|
| 162 |
+
orbital_types = Array{Array{Int64,1},1}(undef, 0)
|
| 163 |
+
basis_dir = joinpath(input_dir, "basis-indices.out")
|
| 164 |
+
@assert ispath(basis_dir)
|
| 165 |
+
f = open(basis_dir)
|
| 166 |
+
readline(f)
|
| 167 |
+
@assert split(readline(f))[1] == "fn."
|
| 168 |
+
basis_indices = zeros(Int64, norbits, 4)
|
| 169 |
+
for index_orbit in 1:norbits
|
| 170 |
+
line = map(x->parse(Int64, x), split(readline(f))[[1, 3, 4, 5, 6]])
|
| 171 |
+
@assert line[1] == index_orbit
|
| 172 |
+
basis_indices[index_orbit, :] = line[2:5]
|
| 173 |
+
# basis_indices: 1 ia, 2 n, 3 l, 4 m
|
| 174 |
+
if size(orbital_types, 1) < line[2]
|
| 175 |
+
orbital_type = Array{Int64,1}(undef, 0)
|
| 176 |
+
push!(orbital_types, orbital_type)
|
| 177 |
+
end
|
| 178 |
+
if line[4] == line[5]
|
| 179 |
+
push!(orbital_types[line[2]], line[4])
|
| 180 |
+
end
|
| 181 |
+
end
|
| 182 |
+
nsites = size(orbital_types, 1)
|
| 183 |
+
site_norbits = (x->sum(x .* 2 .+ 1)).(orbital_types) * (1 + spinful)
|
| 184 |
+
@assert norbits == sum(site_norbits)
|
| 185 |
+
site_norbits_cumsum = cumsum(site_norbits)
|
| 186 |
+
site_indices = zeros(Int64, norbits)
|
| 187 |
+
for index_site in 1:nsites
|
| 188 |
+
if index_site == 1
|
| 189 |
+
site_indices[1:site_norbits_cumsum[index_site]] .= index_site
|
| 190 |
+
else
|
| 191 |
+
site_indices[site_norbits_cumsum[index_site - 1] + 1:site_norbits_cumsum[index_site]] .= index_site
|
| 192 |
+
end
|
| 193 |
+
end
|
| 194 |
+
close(f)
|
| 195 |
+
|
| 196 |
+
f = open(joinpath(input_dir, "geometry.in"))
|
| 197 |
+
# atom_frac_pos = zeros(Float64, 3, nsites)
|
| 198 |
+
element = Array{Int64,1}(undef, 0)
|
| 199 |
+
index_atom = 0
|
| 200 |
+
while !eof(f)
|
| 201 |
+
line = split(readline(f))
|
| 202 |
+
if size(line, 1) > 0 && line[1] == "atom_frac"
|
| 203 |
+
global index_atom
|
| 204 |
+
index_atom += 1
|
| 205 |
+
# atom_frac_pos[:, index_atom] = map(x->parse(Float64, x), line[[2, 3, 4]])
|
| 206 |
+
push!(element, periodic_table[line[5]]["Atomic no"])
|
| 207 |
+
end
|
| 208 |
+
end
|
| 209 |
+
@assert index_atom == nsites
|
| 210 |
+
# site_positions = lat * atom_frac_pos
|
| 211 |
+
close(f)
|
| 212 |
+
|
| 213 |
+
@info string("spinful: ", spinful)
|
| 214 |
+
# write to file
|
| 215 |
+
site_positions = fill(NaN, (3, nsites))
|
| 216 |
+
overlaps_dict = Dict{Array{Int64, 1}, Array{Float64, 2}}()
|
| 217 |
+
positions_dict = Dict{Array{Int64, 1}, Array{Float64, 2}}()
|
| 218 |
+
R_list = Set{Vector{Int64}}()
|
| 219 |
+
if spinful
|
| 220 |
+
hamiltonians_dict = Dict{Array{Int64, 1}, Array{Complex{Float64}, 2}}()
|
| 221 |
+
@error "spinful not implemented yet"
|
| 222 |
+
σx = [0 1; 1 0]
|
| 223 |
+
σy = [0 -im; im 0]
|
| 224 |
+
σz = [1 0; 0 -1]
|
| 225 |
+
σ0 = [1 0; 0 1]
|
| 226 |
+
nm = TBModel{ComplexF64}(2*norbits, lat, isorthogonal=false)
|
| 227 |
+
# convention here is first half up (spin=0); second half down (spin=1).
|
| 228 |
+
for i in 1:size(indexhamiltonian, 1)
|
| 229 |
+
for j in indexhamiltonian[i, 3]:indexhamiltonian[i, 4]
|
| 230 |
+
for nspin in 0:1
|
| 231 |
+
for mspin in 0:1
|
| 232 |
+
sethopping!(nm,
|
| 233 |
+
cellindex[indexhamiltonian[i, 1], :],
|
| 234 |
+
columnindexhamiltonian[j] + norbits * nspin,
|
| 235 |
+
indexhamiltonian[i, 2] + norbits * mspin,
|
| 236 |
+
σ0[nspin + 1, mspin + 1] * hamiltonian[j] -
|
| 237 |
+
(σx[nspin + 1, mspin + 1] * soc_matrix[j, 1] +
|
| 238 |
+
σy[nspin + 1, mspin + 1] * soc_matrix[j, 2] +
|
| 239 |
+
σz[nspin + 1, mspin + 1] * soc_matrix[j, 3]) * im)
|
| 240 |
+
setoverlap!(nm,
|
| 241 |
+
cellindex[indexhamiltonian[i, 1], :],
|
| 242 |
+
columnindexhamiltonian[j] + norbits * nspin,
|
| 243 |
+
indexhamiltonian[i, 2] + norbits * mspin,
|
| 244 |
+
σ0[nspin + 1, mspin + 1] * overlaps[j])
|
| 245 |
+
end
|
| 246 |
+
end
|
| 247 |
+
end
|
| 248 |
+
end
|
| 249 |
+
for i in 1:size(indexhamiltonian, 1)
|
| 250 |
+
for j in indexhamiltonian[i, 3]:indexhamiltonian[i, 4]
|
| 251 |
+
for nspin in 0:1
|
| 252 |
+
for mspin in 0:1
|
| 253 |
+
for dir in 1:3
|
| 254 |
+
setposition!(nm,
|
| 255 |
+
cellindex[indexhamiltonian[i, 1], :],
|
| 256 |
+
columnindexhamiltonian[j] + norbits * nspin,
|
| 257 |
+
indexhamiltonian[i, 2] + norbits * mspin,
|
| 258 |
+
dir,
|
| 259 |
+
σ0[nspin + 1, mspin + 1] * positions[j, dir])
|
| 260 |
+
end
|
| 261 |
+
end
|
| 262 |
+
end
|
| 263 |
+
end
|
| 264 |
+
end
|
| 265 |
+
return nm
|
| 266 |
+
else
|
| 267 |
+
hamiltonians_dict = Dict{Array{Int64, 1}, Array{Float64, 2}}()
|
| 268 |
+
|
| 269 |
+
for i in 1:size(indexhamiltonian, 1)
|
| 270 |
+
for j in indexhamiltonian[i, 3]:indexhamiltonian[i, 4]
|
| 271 |
+
R = cellindex[indexhamiltonian[i, 1], :]
|
| 272 |
+
push!(R_list, SVector{3, Int64}(R))
|
| 273 |
+
orbital_i_whole = columnindexhamiltonian[j]
|
| 274 |
+
orbital_j_whole = indexhamiltonian[i, 2]
|
| 275 |
+
site_i = site_indices[orbital_i_whole]
|
| 276 |
+
site_j = site_indices[orbital_j_whole]
|
| 277 |
+
block_matrix_i = orbital_i_whole - site_norbits_cumsum[site_i] + site_norbits[site_i]
|
| 278 |
+
block_matrix_j = orbital_j_whole - site_norbits_cumsum[site_j] + site_norbits[site_j]
|
| 279 |
+
key = cat(dims=1, R, site_i, site_j)
|
| 280 |
+
key_inv = cat(dims=1, -R, site_j, site_i)
|
| 281 |
+
|
| 282 |
+
mi = 0
|
| 283 |
+
mj = 0
|
| 284 |
+
# p-orbital
|
| 285 |
+
if basis_indices[orbital_i_whole, 3] == 1
|
| 286 |
+
if basis_indices[orbital_i_whole, 4] == -1
|
| 287 |
+
block_matrix_i += 1
|
| 288 |
+
mi = 0
|
| 289 |
+
elseif basis_indices[orbital_i_whole, 4] == 0
|
| 290 |
+
block_matrix_i += 1
|
| 291 |
+
mi = 0
|
| 292 |
+
elseif basis_indices[orbital_i_whole, 4] == 1
|
| 293 |
+
block_matrix_i += -2
|
| 294 |
+
mi = 1
|
| 295 |
+
end
|
| 296 |
+
end
|
| 297 |
+
if basis_indices[orbital_j_whole, 3] == 1
|
| 298 |
+
if basis_indices[orbital_j_whole, 4] == -1
|
| 299 |
+
block_matrix_j += 1
|
| 300 |
+
mj = 0
|
| 301 |
+
elseif basis_indices[orbital_j_whole, 4] == 0
|
| 302 |
+
block_matrix_j += 1
|
| 303 |
+
mj = 0
|
| 304 |
+
elseif basis_indices[orbital_j_whole, 4] == 1
|
| 305 |
+
block_matrix_j += -2
|
| 306 |
+
mj = 1
|
| 307 |
+
end
|
| 308 |
+
end
|
| 309 |
+
# d-orbital
|
| 310 |
+
if basis_indices[orbital_i_whole, 3] == 2
|
| 311 |
+
if basis_indices[orbital_i_whole, 4] == -2
|
| 312 |
+
block_matrix_i += 2
|
| 313 |
+
mi = 0
|
| 314 |
+
elseif basis_indices[orbital_i_whole, 4] == -1
|
| 315 |
+
block_matrix_i += 3
|
| 316 |
+
mi = 0
|
| 317 |
+
elseif basis_indices[orbital_i_whole, 4] == 0
|
| 318 |
+
block_matrix_i += -2
|
| 319 |
+
mi = 0
|
| 320 |
+
elseif basis_indices[orbital_i_whole, 4] == 1
|
| 321 |
+
block_matrix_i += 0
|
| 322 |
+
mi = 1
|
| 323 |
+
elseif basis_indices[orbital_i_whole, 4] == 2
|
| 324 |
+
block_matrix_i += -3
|
| 325 |
+
mi = 0
|
| 326 |
+
end
|
| 327 |
+
end
|
| 328 |
+
if basis_indices[orbital_j_whole, 3] == 2
|
| 329 |
+
if basis_indices[orbital_j_whole, 4] == -2
|
| 330 |
+
block_matrix_j += 2
|
| 331 |
+
mj = 0
|
| 332 |
+
elseif basis_indices[orbital_j_whole, 4] == -1
|
| 333 |
+
block_matrix_j += 3
|
| 334 |
+
mj = 0
|
| 335 |
+
elseif basis_indices[orbital_j_whole, 4] == 0
|
| 336 |
+
block_matrix_j += -2
|
| 337 |
+
mj = 0
|
| 338 |
+
elseif basis_indices[orbital_j_whole, 4] == 1
|
| 339 |
+
block_matrix_j += 0
|
| 340 |
+
mj = 1
|
| 341 |
+
elseif basis_indices[orbital_j_whole, 4] == 2
|
| 342 |
+
block_matrix_j += -3
|
| 343 |
+
mj = 0
|
| 344 |
+
end
|
| 345 |
+
end
|
| 346 |
+
# f-orbital
|
| 347 |
+
if basis_indices[orbital_i_whole, 3] == 3
|
| 348 |
+
if basis_indices[orbital_i_whole, 4] == -3
|
| 349 |
+
block_matrix_i += 6
|
| 350 |
+
mi = 0
|
| 351 |
+
elseif basis_indices[orbital_i_whole, 4] == -2
|
| 352 |
+
block_matrix_i += 3
|
| 353 |
+
mi = 0
|
| 354 |
+
elseif basis_indices[orbital_i_whole, 4] == -1
|
| 355 |
+
block_matrix_i += 0
|
| 356 |
+
mi = 0
|
| 357 |
+
elseif basis_indices[orbital_i_whole, 4] == 0
|
| 358 |
+
block_matrix_i += -3
|
| 359 |
+
mi = 0
|
| 360 |
+
elseif basis_indices[orbital_i_whole, 4] == 1
|
| 361 |
+
block_matrix_i += -3
|
| 362 |
+
mi = 1
|
| 363 |
+
elseif basis_indices[orbital_i_whole, 4] == 2
|
| 364 |
+
block_matrix_i += -2
|
| 365 |
+
mi = 0
|
| 366 |
+
elseif basis_indices[orbital_i_whole, 4] == 3
|
| 367 |
+
block_matrix_i += -1
|
| 368 |
+
mi = 1
|
| 369 |
+
end
|
| 370 |
+
end
|
| 371 |
+
if basis_indices[orbital_j_whole, 3] == 3
|
| 372 |
+
if basis_indices[orbital_j_whole, 4] == -3
|
| 373 |
+
block_matrix_j += 6
|
| 374 |
+
mj = 0
|
| 375 |
+
elseif basis_indices[orbital_j_whole, 4] == -2
|
| 376 |
+
block_matrix_j += 3
|
| 377 |
+
mj = 0
|
| 378 |
+
elseif basis_indices[orbital_j_whole, 4] == -1
|
| 379 |
+
block_matrix_j += 0
|
| 380 |
+
mj = 0
|
| 381 |
+
elseif basis_indices[orbital_j_whole, 4] == 0
|
| 382 |
+
block_matrix_j += -3
|
| 383 |
+
mj = 0
|
| 384 |
+
elseif basis_indices[orbital_j_whole, 4] == 1
|
| 385 |
+
block_matrix_j += -3
|
| 386 |
+
mj = 1
|
| 387 |
+
elseif basis_indices[orbital_j_whole, 4] == 2
|
| 388 |
+
block_matrix_j += -2
|
| 389 |
+
mj = 0
|
| 390 |
+
elseif basis_indices[orbital_j_whole, 4] == 3
|
| 391 |
+
block_matrix_j += -1
|
| 392 |
+
mj = 1
|
| 393 |
+
end
|
| 394 |
+
end
|
| 395 |
+
if (basis_indices[orbital_i_whole, 3] > 3) || (basis_indices[orbital_j_whole, 3] > 3)
|
| 396 |
+
@error("The case of l>3 is not implemented")
|
| 397 |
+
end
|
| 398 |
+
|
| 399 |
+
if !(key ∈ keys(hamiltonians_dict))
|
| 400 |
+
# overlaps_dict[key] = fill(convert(Float64, NaN), (site_norbits[site_i], site_norbits[site_j]))
|
| 401 |
+
overlaps_dict[key] = zeros(Float64, site_norbits[site_i], site_norbits[site_j])
|
| 402 |
+
hamiltonians_dict[key] = zeros(Float64, site_norbits[site_i], site_norbits[site_j])
|
| 403 |
+
for direction in 1:3
|
| 404 |
+
positions_dict[cat(dims=1, key, direction)] = zeros(Float64, site_norbits[site_i], site_norbits[site_j])
|
| 405 |
+
end
|
| 406 |
+
end
|
| 407 |
+
if !(key_inv ∈ keys(hamiltonians_dict))
|
| 408 |
+
overlaps_dict[key_inv] = zeros(Float64, site_norbits[site_j], site_norbits[site_i])
|
| 409 |
+
hamiltonians_dict[key_inv] = zeros(Float64, site_norbits[site_j], site_norbits[site_i])
|
| 410 |
+
for direction in 1:3
|
| 411 |
+
positions_dict[cat(dims=1, key_inv, direction)] = zeros(Float64, site_norbits[site_j], site_norbits[site_i])
|
| 412 |
+
end
|
| 413 |
+
end
|
| 414 |
+
overlaps_dict[key][block_matrix_i, block_matrix_j] = overlaps[j] * (-1) ^ (mi + mj)
|
| 415 |
+
hamiltonians_dict[key][block_matrix_i, block_matrix_j] = hamiltonian[j] * (-1) ^ (mi + mj)
|
| 416 |
+
for direction in 1:3
|
| 417 |
+
positions_dict[cat(dims=1, key, direction)][block_matrix_i, block_matrix_j] = positions[j, direction] * (-1) ^ (mi + mj)
|
| 418 |
+
end
|
| 419 |
+
|
| 420 |
+
overlaps_dict[key_inv][block_matrix_j, block_matrix_i] = overlaps[j] * (-1) ^ (mi + mj)
|
| 421 |
+
hamiltonians_dict[key_inv][block_matrix_j, block_matrix_i] = hamiltonian[j] * (-1) ^ (mi + mj)
|
| 422 |
+
for direction in 1:3
|
| 423 |
+
positions_dict[cat(dims=1, key_inv, direction)][block_matrix_j, block_matrix_i] = positions[j, direction] * (-1) ^ (mi + mj)
|
| 424 |
+
if (R == [0, 0, 0]) && (block_matrix_i == block_matrix_j) && isnan(site_positions[direction, site_i])
|
| 425 |
+
site_positions[direction, site_i] = positions[j, direction]
|
| 426 |
+
end
|
| 427 |
+
end
|
| 428 |
+
end
|
| 429 |
+
end
|
| 430 |
+
end
|
| 431 |
+
|
| 432 |
+
if parsed_args["save_overlap"]
|
| 433 |
+
h5open(joinpath(output_dir, "overlaps.h5"), "w") do fid
|
| 434 |
+
for (key, overlap) in overlaps_dict
|
| 435 |
+
write(fid, string(key), permutedims(overlap))
|
| 436 |
+
end
|
| 437 |
+
end
|
| 438 |
+
end
|
| 439 |
+
h5open(joinpath(output_dir, "hamiltonians.h5"), "w") do fid
|
| 440 |
+
for (key, hamiltonian) in hamiltonians_dict
|
| 441 |
+
write(fid, string(key), permutedims(hamiltonian)) # npz似乎为julia专门做了个转置而h5没有做
|
| 442 |
+
end
|
| 443 |
+
end
|
| 444 |
+
if parsed_args["save_position"]
|
| 445 |
+
h5open(joinpath(output_dir, "positions.h5"), "w") do fid
|
| 446 |
+
for (key, position) in positions_dict
|
| 447 |
+
write(fid, string(key), permutedims(position)) # npz似乎为julia专门做了个转置而h5没有做
|
| 448 |
+
end
|
| 449 |
+
end
|
| 450 |
+
end
|
| 451 |
+
|
| 452 |
+
open(joinpath(output_dir, "orbital_types.dat"), "w") do f
|
| 453 |
+
writedlm(f, orbital_types)
|
| 454 |
+
end
|
| 455 |
+
open(joinpath(output_dir, "lat.dat"), "w") do f
|
| 456 |
+
writedlm(f, lat)
|
| 457 |
+
end
|
| 458 |
+
rlat = 2pi * inv(lat)'
|
| 459 |
+
open(joinpath(output_dir, "rlat.dat"), "w") do f
|
| 460 |
+
writedlm(f, rlat)
|
| 461 |
+
end
|
| 462 |
+
open(joinpath(output_dir, "site_positions.dat"), "w") do f
|
| 463 |
+
writedlm(f, site_positions)
|
| 464 |
+
end
|
| 465 |
+
R_list = collect(R_list)
|
| 466 |
+
open(joinpath(output_dir, "R_list.dat"), "w") do f
|
| 467 |
+
writedlm(f, R_list)
|
| 468 |
+
end
|
| 469 |
+
info_dict = Dict(
|
| 470 |
+
"isspinful" => spinful
|
| 471 |
+
)
|
| 472 |
+
open(joinpath(output_dir, "info.json"), "w") do f
|
| 473 |
+
write(f, json(info_dict, 4))
|
| 474 |
+
end
|
| 475 |
+
open(joinpath(output_dir, "element.dat"), "w") do f
|
| 476 |
+
writedlm(f, element)
|
| 477 |
+
end
|
2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/preprocess/get_rc.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|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
+
|
| 4 |
+
import h5py
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Neighbours:
|
| 10 |
+
def __init__(self):
|
| 11 |
+
self.Rs = []
|
| 12 |
+
self.dists = []
|
| 13 |
+
self.eijs = []
|
| 14 |
+
self.indices = []
|
| 15 |
+
|
| 16 |
+
def __str__(self):
|
| 17 |
+
return 'Rs: {}\ndists: {}\neijs: {}\nindices: {}'.format(
|
| 18 |
+
self.Rs, self.dists, self.indices, self.eijs)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _get_local_coordinate(eij, neighbours_i, gen_rc_idx=False, atom_j=None, atom_j_R=None, r2_rand=False):
|
| 22 |
+
if gen_rc_idx:
|
| 23 |
+
rc_idx = np.full(8, np.nan, dtype=np.int32)
|
| 24 |
+
assert r2_rand is False
|
| 25 |
+
assert atom_j is not None, 'atom_j must be specified when gen_rc_idx is True'
|
| 26 |
+
assert atom_j_R is not None, 'atom_j_R must be specified when gen_rc_idx is True'
|
| 27 |
+
else:
|
| 28 |
+
rc_idx = None
|
| 29 |
+
if r2_rand:
|
| 30 |
+
r2_list = []
|
| 31 |
+
|
| 32 |
+
if not np.allclose(eij.detach(), torch.zeros_like(eij)):
|
| 33 |
+
r1 = eij
|
| 34 |
+
if gen_rc_idx:
|
| 35 |
+
rc_idx[0] = atom_j
|
| 36 |
+
rc_idx[1:4] = atom_j_R
|
| 37 |
+
else:
|
| 38 |
+
r1 = neighbours_i.eijs[1]
|
| 39 |
+
if gen_rc_idx:
|
| 40 |
+
rc_idx[0] = neighbours_i.indices[1]
|
| 41 |
+
rc_idx[1:4] = neighbours_i.Rs[1]
|
| 42 |
+
r2_flag = None
|
| 43 |
+
for r2, r2_index, r2_R in zip(neighbours_i.eijs[1:], neighbours_i.indices[1:], neighbours_i.Rs[1:]):
|
| 44 |
+
if torch.norm(torch.cross(r1, r2)) > 1e-6:
|
| 45 |
+
if gen_rc_idx:
|
| 46 |
+
rc_idx[4] = r2_index
|
| 47 |
+
rc_idx[5:8] = r2_R
|
| 48 |
+
r2_flag = True
|
| 49 |
+
if r2_rand:
|
| 50 |
+
if (len(r2_list) == 0) or (torch.norm(r2_list[0]) + 0.5 > torch.norm(r2)):
|
| 51 |
+
r2_list.append(r2)
|
| 52 |
+
else:
|
| 53 |
+
break
|
| 54 |
+
else:
|
| 55 |
+
break
|
| 56 |
+
assert r2_flag is not None, "There is no linear independent chemical bond in the Rcut range, this may be caused by a too small Rcut or the structure is 1D"
|
| 57 |
+
if r2_rand:
|
| 58 |
+
# print(f"r2 is randomly chosen from {len(r2_list)} candidates")
|
| 59 |
+
r2 = r2_list[np.random.randint(len(r2_list))]
|
| 60 |
+
local_coordinate_1 = r1 / torch.norm(r1)
|
| 61 |
+
local_coordinate_2 = torch.cross(r1, r2) / torch.norm(torch.cross(r1, r2))
|
| 62 |
+
local_coordinate_3 = torch.cross(local_coordinate_1, local_coordinate_2)
|
| 63 |
+
return torch.stack([local_coordinate_1, local_coordinate_2, local_coordinate_3], dim=-1), rc_idx
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def get_rc(input_dir, output_dir, radius, r2_rand=False, gen_rc_idx=False, gen_rc_by_idx="", create_from_DFT=True, neighbour_file='overlaps.h5', if_require_grad=False, cart_coords=None):
|
| 67 |
+
if not if_require_grad:
|
| 68 |
+
assert os.path.exists(os.path.join(input_dir, 'site_positions.dat')), 'No site_positions.dat found in {}'.format(input_dir)
|
| 69 |
+
cart_coords = torch.tensor(np.loadtxt(os.path.join(input_dir, 'site_positions.dat')).T)
|
| 70 |
+
else:
|
| 71 |
+
assert cart_coords is not None, 'cart_coords must be provided if "if_require_grad" is True'
|
| 72 |
+
assert os.path.exists(os.path.join(input_dir, 'lat.dat')), 'No lat.dat found in {}'.format(input_dir)
|
| 73 |
+
lattice = torch.tensor(np.loadtxt(os.path.join(input_dir, 'lat.dat')).T, dtype=cart_coords.dtype)
|
| 74 |
+
|
| 75 |
+
rc_dict = {}
|
| 76 |
+
if gen_rc_idx:
|
| 77 |
+
assert r2_rand is False, 'r2_rand must be False when gen_rc_idx is True'
|
| 78 |
+
assert gen_rc_by_idx == "", 'gen_rc_by_idx must be "" when gen_rc_idx is True'
|
| 79 |
+
rc_idx_dict = {}
|
| 80 |
+
neighbours_dict = {}
|
| 81 |
+
if gen_rc_by_idx != "":
|
| 82 |
+
# print(f'get local coordinate using {os.path.join(gen_rc_by_idx, "rc_idx.h5")} from: {input_dir}')
|
| 83 |
+
assert os.path.exists(os.path.join(gen_rc_by_idx, "rc_idx.h5")), 'Atomic indices for constructing rc rc_idx.h5 is not found in {}'.format(gen_rc_by_idx)
|
| 84 |
+
fid_rc_idx = h5py.File(os.path.join(gen_rc_by_idx, "rc_idx.h5"), 'r')
|
| 85 |
+
for key_str, rc_idx in fid_rc_idx.items():
|
| 86 |
+
key = json.loads(key_str)
|
| 87 |
+
# R = torch.tensor([key[0], key[1], key[2]])
|
| 88 |
+
atom_i = key[3] - 1
|
| 89 |
+
cart_coords_i = cart_coords[atom_i]
|
| 90 |
+
|
| 91 |
+
r1 = cart_coords[rc_idx[0]] + torch.tensor(rc_idx[1:4]).type(cart_coords.dtype) @ lattice - cart_coords_i
|
| 92 |
+
r2 = cart_coords[rc_idx[4]] + torch.tensor(rc_idx[5:8]).type(cart_coords.dtype) @ lattice - cart_coords_i
|
| 93 |
+
local_coordinate_1 = r1 / torch.norm(r1)
|
| 94 |
+
local_coordinate_2 = torch.cross(r1, r2) / torch.norm(torch.cross(r1, r2))
|
| 95 |
+
local_coordinate_3 = torch.cross(local_coordinate_1, local_coordinate_2)
|
| 96 |
+
|
| 97 |
+
rc_dict[key_str] = torch.stack([local_coordinate_1, local_coordinate_2, local_coordinate_3], dim=-1)
|
| 98 |
+
fid_rc_idx.close()
|
| 99 |
+
else:
|
| 100 |
+
# print("get local coordinate from:", input_dir)
|
| 101 |
+
if create_from_DFT:
|
| 102 |
+
assert os.path.exists(os.path.join(input_dir, neighbour_file)), 'No {} found in {}'.format(neighbour_file, input_dir)
|
| 103 |
+
fid_OLP = h5py.File(os.path.join(input_dir, neighbour_file), 'r')
|
| 104 |
+
for key_str in fid_OLP.keys():
|
| 105 |
+
key = json.loads(key_str)
|
| 106 |
+
R = torch.tensor([key[0], key[1], key[2]])
|
| 107 |
+
atom_i = key[3] - 1
|
| 108 |
+
atom_j = key[4] - 1
|
| 109 |
+
cart_coords_i = cart_coords[atom_i]
|
| 110 |
+
cart_coords_j = cart_coords[atom_j] + R.type(cart_coords.dtype) @ lattice
|
| 111 |
+
eij = cart_coords_j - cart_coords_i
|
| 112 |
+
dist = torch.norm(eij)
|
| 113 |
+
if radius > 0 and dist > radius:
|
| 114 |
+
continue
|
| 115 |
+
if atom_i not in neighbours_dict:
|
| 116 |
+
neighbours_dict[atom_i] = Neighbours()
|
| 117 |
+
neighbours_dict[atom_i].Rs.append(R)
|
| 118 |
+
neighbours_dict[atom_i].dists.append(dist)
|
| 119 |
+
neighbours_dict[atom_i].eijs.append(eij)
|
| 120 |
+
neighbours_dict[atom_i].indices.append(atom_j)
|
| 121 |
+
|
| 122 |
+
for atom_i, neighbours_i in neighbours_dict.items():
|
| 123 |
+
neighbours_i.Rs = torch.stack(neighbours_i.Rs)
|
| 124 |
+
neighbours_i.dists = torch.tensor(neighbours_i.dists, dtype=cart_coords.dtype)
|
| 125 |
+
neighbours_i.eijs = torch.stack(neighbours_i.eijs)
|
| 126 |
+
neighbours_i.indices = torch.tensor(neighbours_i.indices)
|
| 127 |
+
|
| 128 |
+
neighbours_i.dists, sorted_index = torch.sort(neighbours_i.dists)
|
| 129 |
+
neighbours_i.Rs = neighbours_i.Rs[sorted_index]
|
| 130 |
+
neighbours_i.eijs = neighbours_i.eijs[sorted_index]
|
| 131 |
+
neighbours_i.indices = neighbours_i.indices[sorted_index]
|
| 132 |
+
|
| 133 |
+
assert np.allclose(neighbours_i.eijs[0].detach(), torch.zeros_like(neighbours_i.eijs[0])), 'eijs[0] should be zero'
|
| 134 |
+
|
| 135 |
+
for R, eij, atom_j, atom_j_R in zip(neighbours_i.Rs, neighbours_i.eijs, neighbours_i.indices, neighbours_i.Rs):
|
| 136 |
+
key_str = str(list([*R.tolist(), atom_i + 1, atom_j.item() + 1]))
|
| 137 |
+
if gen_rc_idx:
|
| 138 |
+
rc_dict[key_str], rc_idx_dict[key_str] = _get_local_coordinate(eij, neighbours_i, gen_rc_idx, atom_j, atom_j_R)
|
| 139 |
+
else:
|
| 140 |
+
rc_dict[key_str] = _get_local_coordinate(eij, neighbours_i, r2_rand=r2_rand)[0]
|
| 141 |
+
else:
|
| 142 |
+
raise NotImplementedError
|
| 143 |
+
|
| 144 |
+
if create_from_DFT:
|
| 145 |
+
fid_OLP.close()
|
| 146 |
+
|
| 147 |
+
if if_require_grad:
|
| 148 |
+
return rc_dict
|
| 149 |
+
else:
|
| 150 |
+
if os.path.exists(os.path.join(output_dir, 'rc_julia.h5')):
|
| 151 |
+
rc_old_flag = True
|
| 152 |
+
fid_rc_old = h5py.File(os.path.join(output_dir, 'rc_julia.h5'), 'r')
|
| 153 |
+
else:
|
| 154 |
+
rc_old_flag = False
|
| 155 |
+
fid_rc = h5py.File(os.path.join(output_dir, 'rc.h5'), 'w')
|
| 156 |
+
for k, v in rc_dict.items():
|
| 157 |
+
if rc_old_flag:
|
| 158 |
+
assert np.allclose(v, fid_rc_old[k][...], atol=1e-4), f"{k}, {v}, {fid_rc_old[k][...]}"
|
| 159 |
+
fid_rc[k] = v
|
| 160 |
+
fid_rc.close()
|
| 161 |
+
if gen_rc_idx:
|
| 162 |
+
fid_rc_idx = h5py.File(os.path.join(output_dir, 'rc_idx.h5'), 'w')
|
| 163 |
+
for k, v in rc_idx_dict.items():
|
| 164 |
+
fid_rc_idx[k] = v
|
| 165 |
+
fid_rc_idx.close()
|
2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/preprocess/openmx_get_data.jl
ADDED
|
@@ -0,0 +1,471 @@
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
using StaticArrays
|
| 2 |
+
using LinearAlgebra
|
| 3 |
+
using HDF5
|
| 4 |
+
using JSON
|
| 5 |
+
using DelimitedFiles
|
| 6 |
+
using Statistics
|
| 7 |
+
using ArgParse
|
| 8 |
+
|
| 9 |
+
function parse_commandline()
|
| 10 |
+
s = ArgParseSettings()
|
| 11 |
+
@add_arg_table! s begin
|
| 12 |
+
"--input_dir", "-i"
|
| 13 |
+
help = ""
|
| 14 |
+
arg_type = String
|
| 15 |
+
default = "./"
|
| 16 |
+
"--output_dir", "-o"
|
| 17 |
+
help = ""
|
| 18 |
+
arg_type = String
|
| 19 |
+
default = "./output"
|
| 20 |
+
"--if_DM", "-d"
|
| 21 |
+
help = ""
|
| 22 |
+
arg_type = Bool
|
| 23 |
+
default = false
|
| 24 |
+
"--save_overlap", "-s"
|
| 25 |
+
help = ""
|
| 26 |
+
arg_type = Bool
|
| 27 |
+
default = false
|
| 28 |
+
end
|
| 29 |
+
return parse_args(s)
|
| 30 |
+
end
|
| 31 |
+
parsed_args = parse_commandline()
|
| 32 |
+
|
| 33 |
+
# @info string("get data from: ", parsed_args["input_dir"])
|
| 34 |
+
periodic_table = JSON.parsefile(joinpath(@__DIR__, "periodic_table.json"))
|
| 35 |
+
|
| 36 |
+
#=
|
| 37 |
+
struct Site_list
|
| 38 |
+
R::Array{StaticArrays.SArray{Tuple{3},Int16,1,3},1}
|
| 39 |
+
site::Array{Int64,1}
|
| 40 |
+
pos::Array{Float64,2}
|
| 41 |
+
end
|
| 42 |
+
|
| 43 |
+
function _cal_neighbour_site(e_ij::Array{Float64,2},Rcut::Float64)
|
| 44 |
+
r_ij = sum(dims=1,e_ij.^2)[1,:]
|
| 45 |
+
p = sortperm(r_ij)
|
| 46 |
+
j_cut = searchsorted(r_ij[p],Rcut^2).stop
|
| 47 |
+
return p[1:j_cut]
|
| 48 |
+
end
|
| 49 |
+
|
| 50 |
+
function cal_neighbour_site(site_positions::Matrix{<:Real}, lat::Matrix{<:Real}, R_list::Union{Vector{SVector{3, Int64}}, Vector{Vector{Int64}}}, nsites::Int64, Rcut::Float64)
|
| 51 |
+
# writed by lihe
|
| 52 |
+
neighbour_site = Array{Site_list,1}([])
|
| 53 |
+
# R_list = collect(keys(tm.hoppings))
|
| 54 |
+
pos_R_list = map(R -> collect(lat * R), R_list)
|
| 55 |
+
pos_j_list = cat(dims=2, map(pos_R -> pos_R .+ site_positions, pos_R_list)...)
|
| 56 |
+
for site_i in 1:nsites
|
| 57 |
+
pos_i = site_positions[:, site_i]
|
| 58 |
+
e_ij = pos_j_list .- pos_i
|
| 59 |
+
p = _cal_neighbour_site(e_ij, Rcut)
|
| 60 |
+
R_ordered = R_list[map(x -> div(x + (nsites - 1), nsites),p)]
|
| 61 |
+
site_ordered = map(x -> mod(x - 1, nsites) + 1,p)
|
| 62 |
+
pos_ordered = e_ij[:,p]
|
| 63 |
+
@assert pos_ordered[:,1] ≈ [0,0,0]
|
| 64 |
+
push!(neighbour_site, Site_list(R_ordered, site_ordered, pos_ordered))
|
| 65 |
+
end
|
| 66 |
+
return neighbour_site
|
| 67 |
+
end
|
| 68 |
+
|
| 69 |
+
function _get_local_coordinate(e_ij::Array{Float64,1},site_list_i::Site_list)
|
| 70 |
+
if e_ij != [0,0,0]
|
| 71 |
+
r1 = e_ij
|
| 72 |
+
else
|
| 73 |
+
r1 = site_list_i.pos[:,2]
|
| 74 |
+
end
|
| 75 |
+
nsites_i = length(site_list_i.R)
|
| 76 |
+
r2 = [0,0,0]
|
| 77 |
+
for j in 1:nsites_i
|
| 78 |
+
r2 = site_list_i.pos[:,j]
|
| 79 |
+
if norm(cross(r1,r2)) != 0
|
| 80 |
+
break
|
| 81 |
+
end
|
| 82 |
+
if j == nsites_i
|
| 83 |
+
for k in 1:3
|
| 84 |
+
r2 = [[1,0,0],[0,1,0],[0,0,1]][k]
|
| 85 |
+
if norm(cross(r1,r2)) != 0
|
| 86 |
+
break
|
| 87 |
+
end
|
| 88 |
+
end
|
| 89 |
+
end
|
| 90 |
+
end
|
| 91 |
+
if r2 == [0,0,0]
|
| 92 |
+
error("there is no linear independent chemical bond in the Rcut range, this may be caused by a too small Rcut or the structure is1D")
|
| 93 |
+
end
|
| 94 |
+
local_coordinate = zeros(Float64,(3,3))
|
| 95 |
+
local_coordinate[:,1] = r1/norm(r1)
|
| 96 |
+
|
| 97 |
+
local_coordinate[:,2] = cross(r1,r2)/norm(cross(r1,r2))
|
| 98 |
+
local_coordinate[:,3] = cross(local_coordinate[:,1],local_coordinate[:,2])
|
| 99 |
+
return local_coordinate
|
| 100 |
+
end
|
| 101 |
+
|
| 102 |
+
function get_local_coordinates(site_positions::Matrix{<:Real}, lat::Matrix{<:Real}, R_list::Vector{SVector{3, Int64}}, Rcut::Float64)::Dict{Array{Int64,1},Array{Float64,2}}
|
| 103 |
+
nsites = size(site_positions, 2)
|
| 104 |
+
neighbour_site = cal_neighbour_site(site_positions, lat, R_list, nsites, Rcut)
|
| 105 |
+
local_coordinates = Dict{Array{Int64,1},Array{Float64,2}}()
|
| 106 |
+
for site_i = 1:nsites
|
| 107 |
+
site_list_i = neighbour_site[site_i]
|
| 108 |
+
nsites_i = length(site_list_i.R)
|
| 109 |
+
for j = 1:nsites_i
|
| 110 |
+
R = site_list_i.R[j]; site_j = site_list_i.site[j]; e_ij = site_list_i.pos[:,j]
|
| 111 |
+
local_coordinate = _get_local_coordinate(e_ij, site_list_i)
|
| 112 |
+
local_coordinates[cat(dims=1, R, site_i, site_j)] = local_coordinate
|
| 113 |
+
end
|
| 114 |
+
end
|
| 115 |
+
return local_coordinates
|
| 116 |
+
end
|
| 117 |
+
=#
|
| 118 |
+
|
| 119 |
+
# The function parse_openmx below is come from "https://github.com/HopTB/HopTB.jl"
|
| 120 |
+
function parse_openmx(filepath::String; return_DM::Bool = false)
|
| 121 |
+
# define some helper functions for mixed structure of OpenMX binary data file.
|
| 122 |
+
function multiread(::Type{T}, f, size)::Vector{T} where T
|
| 123 |
+
ret = Vector{T}(undef, size)
|
| 124 |
+
read!(f, ret);ret
|
| 125 |
+
end
|
| 126 |
+
multiread(f, size) = multiread(Int32, f, size)
|
| 127 |
+
|
| 128 |
+
function read_mixed_matrix(::Type{T}, f, dims::Vector{<:Integer}) where T
|
| 129 |
+
ret::Vector{Vector{T}} = []
|
| 130 |
+
for i = dims; t = Vector{T}(undef, i);read!(f, t);push!(ret, t); end; ret
|
| 131 |
+
end
|
| 132 |
+
|
| 133 |
+
function read_matrix_in_mixed_matrix(::Type{T}, f, spins, atomnum, FNAN, natn, Total_NumOrbs) where T
|
| 134 |
+
ret = Vector{Vector{Vector{Matrix{T}}}}(undef, spins)
|
| 135 |
+
for spin = 1:spins;t_spin = Vector{Vector{Matrix{T}}}(undef, atomnum)
|
| 136 |
+
for ai = 1:atomnum;t_ai = Vector{Matrix{T}}(undef, FNAN[ai])
|
| 137 |
+
for aj_inner = 1:FNAN[ai]
|
| 138 |
+
t = Matrix{T}(undef, Total_NumOrbs[natn[ai][aj_inner]], Total_NumOrbs[ai])
|
| 139 |
+
read!(f, t);t_ai[aj_inner] = t
|
| 140 |
+
end;t_spin[ai] = t_ai
|
| 141 |
+
end;ret[spin] = t_spin
|
| 142 |
+
end;return ret
|
| 143 |
+
end
|
| 144 |
+
read_matrix_in_mixed_matrix(f, spins, atomnum, FNAN, natn, Total_NumOrbs) = read_matrix_in_mixed_matrix(Float64, f, spins, atomnum, FNAN, natn, Total_NumOrbs)
|
| 145 |
+
|
| 146 |
+
read_3d_vecs(::Type{T}, f, num) where T = reshape(multiread(T, f, 4 * num), 4, Int(num))[2:4,:]
|
| 147 |
+
read_3d_vecs(f, num) = read_3d_vecs(Float64, f, num)
|
| 148 |
+
# End of helper functions
|
| 149 |
+
|
| 150 |
+
bound_multiread(T, size) = multiread(T, f, size)
|
| 151 |
+
bound_multiread(size) = multiread(f, size)
|
| 152 |
+
bound_read_mixed_matrix() = read_mixed_matrix(Int32, f, FNAN)
|
| 153 |
+
bound_read_matrix_in_mixed_matrix(spins) = read_matrix_in_mixed_matrix(f, spins, atomnum, FNAN, natn, Total_NumOrbs)
|
| 154 |
+
bound_read_3d_vecs(num) = read_3d_vecs(f, num)
|
| 155 |
+
bound_read_3d_vecs(::Type{T}, num) where T = read_3d_vecs(T, f, num)
|
| 156 |
+
# End of bound helper functions
|
| 157 |
+
|
| 158 |
+
f = open(filepath)
|
| 159 |
+
atomnum, SpinP_switch, Catomnum, Latomnum, Ratomnum, TCpyCell, order_max = bound_multiread(7)
|
| 160 |
+
@assert (SpinP_switch >> 2) == 3 "DeepH-pack only supports OpenMX v3.9. Please check your OpenMX version"
|
| 161 |
+
SpinP_switch &= 0x03
|
| 162 |
+
|
| 163 |
+
atv, atv_ijk = bound_read_3d_vecs.([Float64,Int32], TCpyCell + 1)
|
| 164 |
+
|
| 165 |
+
Total_NumOrbs, FNAN = bound_multiread.([atomnum,atomnum])
|
| 166 |
+
FNAN .+= 1
|
| 167 |
+
natn = bound_read_mixed_matrix()
|
| 168 |
+
ncn = ((x)->x .+ 1).(bound_read_mixed_matrix()) # These is to fix that atv and atv_ijk starts from 0 in original C code.
|
| 169 |
+
|
| 170 |
+
tv, rtv, Gxyz = bound_read_3d_vecs.([3,3,atomnum])
|
| 171 |
+
|
| 172 |
+
Hk = bound_read_matrix_in_mixed_matrix(SpinP_switch + 1)
|
| 173 |
+
iHk = SpinP_switch == 3 ? bound_read_matrix_in_mixed_matrix(3) : nothing
|
| 174 |
+
OLP = bound_read_matrix_in_mixed_matrix(1)[1]
|
| 175 |
+
OLP_r = []
|
| 176 |
+
for dir in 1:3, order in 1:order_max
|
| 177 |
+
t = bound_read_matrix_in_mixed_matrix(1)[1]
|
| 178 |
+
if order == 1 push!(OLP_r, t) end
|
| 179 |
+
end
|
| 180 |
+
OLP_p = bound_read_matrix_in_mixed_matrix(3)
|
| 181 |
+
DM = bound_read_matrix_in_mixed_matrix(SpinP_switch + 1)
|
| 182 |
+
iDM = bound_read_matrix_in_mixed_matrix(2)
|
| 183 |
+
solver = bound_multiread(1)[1]
|
| 184 |
+
chem_p, E_temp = bound_multiread(Float64, 2)
|
| 185 |
+
dipole_moment_core, dipole_moment_background = bound_multiread.(Float64, [3,3])
|
| 186 |
+
Valence_Electrons, Total_SpinS = bound_multiread(Float64, 2)
|
| 187 |
+
dummy_blocks = bound_multiread(1)[1]
|
| 188 |
+
for i in 1:dummy_blocks
|
| 189 |
+
bound_multiread(UInt8, 256)
|
| 190 |
+
end
|
| 191 |
+
|
| 192 |
+
# we suppose that the original output file(.out) was appended to the end of the scfout file.
|
| 193 |
+
function strip1(s::Vector{UInt8})
|
| 194 |
+
startpos = 0
|
| 195 |
+
for i = 1:length(s) + 1
|
| 196 |
+
if i > length(s) || s[i] & 0x80 != 0 || !isspace(Char(s[i] & 0x7f))
|
| 197 |
+
startpos = i
|
| 198 |
+
break
|
| 199 |
+
end
|
| 200 |
+
end
|
| 201 |
+
return s[startpos:end]
|
| 202 |
+
end
|
| 203 |
+
function startswith1(s::Vector{UInt8}, prefix::Vector{UInt8})
|
| 204 |
+
return length(s) >= length(prefix) && s[1:length(prefix)] == prefix
|
| 205 |
+
end
|
| 206 |
+
function isnum(s::Char)
|
| 207 |
+
if s >= '1' && s <= '9'
|
| 208 |
+
return true
|
| 209 |
+
else
|
| 210 |
+
return false
|
| 211 |
+
end
|
| 212 |
+
end
|
| 213 |
+
|
| 214 |
+
function isorb(s::Char)
|
| 215 |
+
if s in ['s','p','d','f']
|
| 216 |
+
return true
|
| 217 |
+
else
|
| 218 |
+
return false
|
| 219 |
+
end
|
| 220 |
+
end
|
| 221 |
+
|
| 222 |
+
function orbital_types_str2num(str::AbstractString)
|
| 223 |
+
orbs = split(str, isnum, keepempty = false)
|
| 224 |
+
nums = map(x->parse(Int, x), split(str, isorb, keepempty = false))
|
| 225 |
+
orb2l = Dict("s" => 0, "p" => 1, "d" => 2, "f" => 3)
|
| 226 |
+
@assert length(orbs) == length(nums)
|
| 227 |
+
orbital_types = Array{Int64,1}(undef, 0)
|
| 228 |
+
for (orb, num) in zip(orbs, nums)
|
| 229 |
+
for i = 1:num
|
| 230 |
+
push!(orbital_types, orb2l[orb])
|
| 231 |
+
end
|
| 232 |
+
end
|
| 233 |
+
return orbital_types
|
| 234 |
+
end
|
| 235 |
+
|
| 236 |
+
function find_target_line(target_line::String)
|
| 237 |
+
target_line_UInt8 = Vector{UInt8}(target_line)
|
| 238 |
+
while !startswith1(strip1(Vector{UInt8}(readline(f))), target_line_UInt8)
|
| 239 |
+
if eof(f)
|
| 240 |
+
error(string(target_line, "not found. Please check if the .out file was appended to the end of .scfout file!"))
|
| 241 |
+
end
|
| 242 |
+
end
|
| 243 |
+
end
|
| 244 |
+
|
| 245 |
+
# @info """get orbital setting of element:orbital_types_element::Dict{String,Array{Int64,1}} "element" => orbital_types"""
|
| 246 |
+
find_target_line("<Definition.of.Atomic.Species")
|
| 247 |
+
orbital_types_element = Dict{String,Array{Int64,1}}([])
|
| 248 |
+
while true
|
| 249 |
+
str = readline(f)
|
| 250 |
+
if str == "Definition.of.Atomic.Species>"
|
| 251 |
+
break
|
| 252 |
+
end
|
| 253 |
+
element = split(str)[1]
|
| 254 |
+
orbital_types_str = split(split(str)[2], "-")[2]
|
| 255 |
+
orbital_types_element[element] = orbital_types_str2num(orbital_types_str)
|
| 256 |
+
end
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
# @info "get Chemical potential (Hartree)"
|
| 260 |
+
find_target_line("(see also PRB 72, 045121(2005) for the energy contributions)")
|
| 261 |
+
readline(f)
|
| 262 |
+
readline(f)
|
| 263 |
+
readline(f)
|
| 264 |
+
str = split(readline(f))
|
| 265 |
+
@assert "Chemical" == str[1]
|
| 266 |
+
@assert "potential" == str[2]
|
| 267 |
+
@assert "(Hartree)" == str[3]
|
| 268 |
+
ev2Hartree = 0.036749324533634074
|
| 269 |
+
fermi_level = parse(Float64, str[length(str)])/ev2Hartree
|
| 270 |
+
|
| 271 |
+
# @info "get Chemical potential (Hartree)"
|
| 272 |
+
# find_target_line("Eigenvalues (Hartree)")
|
| 273 |
+
# for i = 1:2;@assert readline(f) == "***********************************************************";end
|
| 274 |
+
# readline(f)
|
| 275 |
+
# str = split(readline(f))
|
| 276 |
+
# ev2Hartree = 0.036749324533634074
|
| 277 |
+
# fermi_level = parse(Float64, str[length(str)])/ev2Hartree
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
# @info "get Fractional coordinates & orbital types:"
|
| 281 |
+
find_target_line("Fractional coordinates of the final structure")
|
| 282 |
+
target_line = Vector{UInt8}("Fractional coordinates of the final structure")
|
| 283 |
+
for i = 1:2;@assert readline(f) == "***********************************************************";end
|
| 284 |
+
@assert readline(f) == ""
|
| 285 |
+
orbital_types = Array{Array{Int64,1},1}(undef, 0) #orbital_types
|
| 286 |
+
element = Array{Int64,1}(undef, 0) #orbital_types
|
| 287 |
+
atom_frac_pos = zeros(3, atomnum) #Fractional coordinates
|
| 288 |
+
for i = 1:atomnum
|
| 289 |
+
str = readline(f)
|
| 290 |
+
element_str = split(str)[2]
|
| 291 |
+
push!(orbital_types, orbital_types_element[element_str])
|
| 292 |
+
m = match(r"^\s*\d+\s+\w+\s+([0-9+-.Ee]+)\s+([0-9+-.Ee]+)\s+([0-9+-.Ee]+)", str)
|
| 293 |
+
push!(element, periodic_table[element_str]["Atomic no"])
|
| 294 |
+
atom_frac_pos[:,i] = ((x)->parse(Float64, x)).(m.captures)
|
| 295 |
+
end
|
| 296 |
+
atom_pos = tv * atom_frac_pos
|
| 297 |
+
close(f)
|
| 298 |
+
|
| 299 |
+
# use the atom_pos to fix
|
| 300 |
+
# TODO: Persuade wangc to accept the following code, which seems hopeless and meaningless.
|
| 301 |
+
"""
|
| 302 |
+
for axis = 1:3
|
| 303 |
+
((x2, y2, z)->((x, y)->x .+= z * y).(x2, y2)).(OLP_r[axis], OLP, atom_pos[axis,:])
|
| 304 |
+
end
|
| 305 |
+
"""
|
| 306 |
+
for axis in 1:3,i in 1:atomnum, j in 1:FNAN[i]
|
| 307 |
+
OLP_r[axis][i][j] .+= atom_pos[axis,i] * OLP[i][j]
|
| 308 |
+
end
|
| 309 |
+
|
| 310 |
+
# fix type mismatch
|
| 311 |
+
atv_ijk = Matrix{Int64}(atv_ijk)
|
| 312 |
+
|
| 313 |
+
if return_DM
|
| 314 |
+
return element, atomnum, SpinP_switch, atv, atv_ijk, Total_NumOrbs, FNAN, natn, ncn, tv, Hk, iHk, OLP, OLP_r, orbital_types, fermi_level, atom_pos, DM
|
| 315 |
+
else
|
| 316 |
+
return element, atomnum, SpinP_switch, atv, atv_ijk, Total_NumOrbs, FNAN, natn, ncn, tv, Hk, iHk, OLP, OLP_r, orbital_types, fermi_level, atom_pos, nothing
|
| 317 |
+
end
|
| 318 |
+
end
|
| 319 |
+
|
| 320 |
+
function get_data(filepath_scfout::String, Rcut::Float64; if_DM::Bool = false)
|
| 321 |
+
element, nsites, SpinP_switch, atv, atv_ijk, Total_NumOrbs, FNAN, natn, ncn, lat, Hk, iHk, OLP, OLP_r, orbital_types, fermi_level, site_positions, DM = parse_openmx(filepath_scfout; return_DM=if_DM)
|
| 322 |
+
|
| 323 |
+
for t in [Hk, iHk]
|
| 324 |
+
if t != nothing
|
| 325 |
+
((x)->((y)->((z)->z .*= 27.2113845).(y)).(x)).(t) # Hartree to eV
|
| 326 |
+
end
|
| 327 |
+
end
|
| 328 |
+
site_positions .*= 0.529177249 # Bohr to Ang
|
| 329 |
+
lat .*= 0.529177249 # Bohr to Ang
|
| 330 |
+
|
| 331 |
+
# get R_list
|
| 332 |
+
R_list = Set{Vector{Int64}}()
|
| 333 |
+
for atom_i in 1:nsites, index_nn_i in 1:FNAN[atom_i]
|
| 334 |
+
atom_j = natn[atom_i][index_nn_i]
|
| 335 |
+
R = atv_ijk[:, ncn[atom_i][index_nn_i]]
|
| 336 |
+
push!(R_list, SVector{3, Int64}(R))
|
| 337 |
+
end
|
| 338 |
+
R_list = collect(R_list)
|
| 339 |
+
|
| 340 |
+
# get neighbour_site
|
| 341 |
+
nsites = size(site_positions, 2)
|
| 342 |
+
# neighbour_site = cal_neighbour_site(site_positions, lat, R_list, nsites, Rcut)
|
| 343 |
+
# local_coordinates = Dict{Array{Int64, 1}, Array{Float64, 2}}()
|
| 344 |
+
|
| 345 |
+
# process hamiltonian
|
| 346 |
+
norbits = sum(Total_NumOrbs)
|
| 347 |
+
overlaps = Dict{Array{Int64, 1}, Array{Float64, 2}}()
|
| 348 |
+
if SpinP_switch == 0
|
| 349 |
+
spinful = false
|
| 350 |
+
hamiltonians = Dict{Array{Int64, 1}, Array{Float64, 2}}()
|
| 351 |
+
if if_DM
|
| 352 |
+
density_matrixs = Dict{Array{Int64, 1}, Array{Float64, 2}}()
|
| 353 |
+
else
|
| 354 |
+
density_matrixs = nothing
|
| 355 |
+
end
|
| 356 |
+
elseif SpinP_switch == 1
|
| 357 |
+
error("Collinear spin is not supported currently")
|
| 358 |
+
elseif SpinP_switch == 3
|
| 359 |
+
@assert if_DM == false
|
| 360 |
+
density_matrixs = nothing
|
| 361 |
+
spinful = true
|
| 362 |
+
for i in 1:length(Hk[4]),j in 1:length(Hk[4][i])
|
| 363 |
+
Hk[4][i][j] += iHk[3][i][j]
|
| 364 |
+
iHk[3][i][j] = -Hk[4][i][j]
|
| 365 |
+
end
|
| 366 |
+
hamiltonians = Dict{Array{Int64, 1}, Array{Complex{Float64}, 2}}()
|
| 367 |
+
else
|
| 368 |
+
error("SpinP_switch is $SpinP_switch, rather than valid values 0, 1 or 3")
|
| 369 |
+
end
|
| 370 |
+
|
| 371 |
+
for site_i in 1:nsites, index_nn_i in 1:FNAN[site_i]
|
| 372 |
+
site_j = natn[site_i][index_nn_i]
|
| 373 |
+
R = atv_ijk[:, ncn[site_i][index_nn_i]]
|
| 374 |
+
e_ij = lat * R + site_positions[:, site_j] - site_positions[:, site_i]
|
| 375 |
+
# if norm(e_ij) > Rcut
|
| 376 |
+
# continue
|
| 377 |
+
# end
|
| 378 |
+
key = cat(dims=1, R, site_i, site_j)
|
| 379 |
+
# site_list_i = neighbour_site[site_i]
|
| 380 |
+
# local_coordinate = _get_local_coordinate(e_ij, site_list_i)
|
| 381 |
+
# local_coordinates[key] = local_coordinate
|
| 382 |
+
|
| 383 |
+
overlap = permutedims(OLP[site_i][index_nn_i])
|
| 384 |
+
overlaps[key] = overlap
|
| 385 |
+
if SpinP_switch == 0
|
| 386 |
+
hamiltonian = permutedims(Hk[1][site_i][index_nn_i])
|
| 387 |
+
hamiltonians[key] = hamiltonian
|
| 388 |
+
if if_DM
|
| 389 |
+
density_matrix = permutedims(DM[1][site_i][index_nn_i])
|
| 390 |
+
density_matrixs[key] = density_matrix
|
| 391 |
+
end
|
| 392 |
+
elseif SpinP_switch == 1
|
| 393 |
+
error("Collinear spin is not supported currently")
|
| 394 |
+
elseif SpinP_switch == 3
|
| 395 |
+
key_inv = cat(dims=1, -R, site_j, site_i)
|
| 396 |
+
|
| 397 |
+
len_i_wo_spin = Total_NumOrbs[site_i]
|
| 398 |
+
len_j_wo_spin = Total_NumOrbs[site_j]
|
| 399 |
+
|
| 400 |
+
if !(key in keys(hamiltonians))
|
| 401 |
+
@assert !(key_inv in keys(hamiltonians))
|
| 402 |
+
hamiltonians[key] = zeros(Complex{Float64}, len_i_wo_spin * 2, len_j_wo_spin * 2)
|
| 403 |
+
hamiltonians[key_inv] = zeros(Complex{Float64}, len_j_wo_spin * 2, len_i_wo_spin * 2)
|
| 404 |
+
end
|
| 405 |
+
for spini in 0:1,spinj in spini:1
|
| 406 |
+
Hk_real, Hk_imag = spini == 0 ? spinj == 0 ? (Hk[1][site_i][index_nn_i], iHk[1][site_i][index_nn_i]) : (Hk[3][site_i][index_nn_i], Hk[4][site_i][index_nn_i]) : spinj == 0 ? (Hk[3][site_i][index_nn_i], iHk[3][site_i][index_nn_i]) : (Hk[2][site_i][index_nn_i], iHk[2][site_i][index_nn_i])
|
| 407 |
+
hamiltonians[key][spini * len_i_wo_spin + 1 : (spini + 1) * len_i_wo_spin, spinj * len_j_wo_spin + 1 : (spinj + 1) * len_j_wo_spin] = permutedims(Hk_real) + im * permutedims(Hk_imag)
|
| 408 |
+
if spini == 0 && spinj == 1
|
| 409 |
+
hamiltonians[key_inv][1 * len_j_wo_spin + 1 : (1 + 1) * len_j_wo_spin, 0 * len_i_wo_spin + 1 : (0 + 1) * len_i_wo_spin] = (permutedims(Hk_real) + im * permutedims(Hk_imag))'
|
| 410 |
+
end
|
| 411 |
+
end
|
| 412 |
+
else
|
| 413 |
+
error("SpinP_switch is $SpinP_switch, rather than valid values 0, 1 or 3")
|
| 414 |
+
end
|
| 415 |
+
end
|
| 416 |
+
|
| 417 |
+
return element, overlaps, density_matrixs, hamiltonians, fermi_level, orbital_types, lat, site_positions, spinful, R_list
|
| 418 |
+
end
|
| 419 |
+
|
| 420 |
+
parsed_args["input_dir"] = abspath(parsed_args["input_dir"])
|
| 421 |
+
mkpath(parsed_args["output_dir"])
|
| 422 |
+
cd(parsed_args["output_dir"])
|
| 423 |
+
|
| 424 |
+
element, overlaps, density_matrixs, hamiltonians, fermi_level, orbital_types, lat, site_positions, spinful, R_list = get_data(joinpath(parsed_args["input_dir"], "openmx.scfout"), -1.0; if_DM=parsed_args["if_DM"])
|
| 425 |
+
|
| 426 |
+
if parsed_args["if_DM"]
|
| 427 |
+
h5open("density_matrixs.h5", "w") do fid
|
| 428 |
+
for (key, density_matrix) in density_matrixs
|
| 429 |
+
write(fid, string(key), permutedims(density_matrix))
|
| 430 |
+
end
|
| 431 |
+
end
|
| 432 |
+
end
|
| 433 |
+
if parsed_args["save_overlap"]
|
| 434 |
+
h5open("overlaps.h5", "w") do fid
|
| 435 |
+
for (key, overlap) in overlaps
|
| 436 |
+
write(fid, string(key), permutedims(overlap))
|
| 437 |
+
end
|
| 438 |
+
end
|
| 439 |
+
end
|
| 440 |
+
h5open("hamiltonians.h5", "w") do fid
|
| 441 |
+
for (key, hamiltonian) in hamiltonians
|
| 442 |
+
write(fid, string(key), permutedims(hamiltonian))
|
| 443 |
+
end
|
| 444 |
+
end
|
| 445 |
+
|
| 446 |
+
info_dict = Dict(
|
| 447 |
+
"fermi_level" => fermi_level,
|
| 448 |
+
"isspinful" => spinful
|
| 449 |
+
)
|
| 450 |
+
open("info.json", "w") do f
|
| 451 |
+
write(f, json(info_dict, 4))
|
| 452 |
+
end
|
| 453 |
+
open("site_positions.dat", "w") do f
|
| 454 |
+
writedlm(f, site_positions)
|
| 455 |
+
end
|
| 456 |
+
open("R_list.dat", "w") do f
|
| 457 |
+
writedlm(f, R_list)
|
| 458 |
+
end
|
| 459 |
+
open("lat.dat", "w") do f
|
| 460 |
+
writedlm(f, lat)
|
| 461 |
+
end
|
| 462 |
+
rlat = 2pi * inv(lat)'
|
| 463 |
+
open("rlat.dat", "w") do f
|
| 464 |
+
writedlm(f, rlat)
|
| 465 |
+
end
|
| 466 |
+
open("orbital_types.dat", "w") do f
|
| 467 |
+
writedlm(f, orbital_types)
|
| 468 |
+
end
|
| 469 |
+
open("element.dat", "w") do f
|
| 470 |
+
writedlm(f, element)
|
| 471 |
+
end
|
2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/preprocess/openmx_parse.py
ADDED
|
@@ -0,0 +1,425 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
from math import pi
|
| 4 |
+
|
| 5 |
+
import tqdm
|
| 6 |
+
import argparse
|
| 7 |
+
import h5py
|
| 8 |
+
import numpy as np
|
| 9 |
+
from pymatgen.core.structure import Structure
|
| 10 |
+
|
| 11 |
+
from .abacus_get_data import periodic_table
|
| 12 |
+
|
| 13 |
+
Hartree2Ev = 27.2113845
|
| 14 |
+
Ev2Kcalmol = 23.061
|
| 15 |
+
Bohr2R = 0.529177249
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def openmx_force_intferface(out_file_dir, save_dir=None, return_Etot=False, return_force=False):
|
| 19 |
+
with open(out_file_dir, 'r') as out_file:
|
| 20 |
+
lines = out_file.readlines()
|
| 21 |
+
for index_line, line in enumerate(lines):
|
| 22 |
+
if line.find('Total energy (Hartree) at MD = 1') != -1:
|
| 23 |
+
assert lines[index_line + 3].find("Uele.") != -1
|
| 24 |
+
assert lines[index_line + 5].find("Ukin.") != -1
|
| 25 |
+
assert lines[index_line + 7].find("UH1.") != -1
|
| 26 |
+
assert lines[index_line + 8].find("Una.") != -1
|
| 27 |
+
assert lines[index_line + 9].find("Unl.") != -1
|
| 28 |
+
assert lines[index_line + 10].find("Uxc0.") != -1
|
| 29 |
+
assert lines[index_line + 20].find("Utot.") != -1
|
| 30 |
+
parse_E = lambda x: float(x.split()[-1])
|
| 31 |
+
E_tot = parse_E(lines[index_line + 20]) * Hartree2Ev
|
| 32 |
+
E_kin = parse_E(lines[index_line + 5]) * Hartree2Ev
|
| 33 |
+
E_delta_ee = parse_E(lines[index_line + 7]) * Hartree2Ev
|
| 34 |
+
E_NA = parse_E(lines[index_line + 8]) * Hartree2Ev
|
| 35 |
+
E_NL = parse_E(lines[index_line + 9]) * Hartree2Ev
|
| 36 |
+
E_xc = parse_E(lines[index_line + 10]) * 2 * Hartree2Ev
|
| 37 |
+
if save_dir is not None:
|
| 38 |
+
with open(os.path.join(save_dir, "openmx_E.json"), 'w') as E_file:
|
| 39 |
+
json.dump({
|
| 40 |
+
"Total energy": E_tot,
|
| 41 |
+
"E_kin": E_kin,
|
| 42 |
+
"E_delta_ee": E_delta_ee,
|
| 43 |
+
"E_NA": E_NA,
|
| 44 |
+
"E_NL": E_NL,
|
| 45 |
+
"E_xc": E_xc
|
| 46 |
+
}, E_file)
|
| 47 |
+
if line.find('xyz-coordinates (Ang) and forces (Hartree/Bohr)') != -1:
|
| 48 |
+
assert lines[index_line + 4].find("<coordinates.forces") != -1
|
| 49 |
+
num_atom = int(lines[index_line + 5])
|
| 50 |
+
forces = np.zeros((num_atom, 3))
|
| 51 |
+
for index_atom in range(num_atom):
|
| 52 |
+
forces[index_atom] = list(
|
| 53 |
+
map(lambda x: float(x) * Hartree2Ev / Bohr2R, lines[index_line + 6 + index_atom].split()[-3:]))
|
| 54 |
+
break
|
| 55 |
+
if save_dir is not None:
|
| 56 |
+
np.savetxt(os.path.join(save_dir, "openmx_forces.dat"), forces)
|
| 57 |
+
ret = (E_kin, E_delta_ee, E_NA, E_NL, E_xc)
|
| 58 |
+
if return_Etot is True:
|
| 59 |
+
ret = ret + (E_tot,)
|
| 60 |
+
if return_force is True:
|
| 61 |
+
ret = ret + (forces,)
|
| 62 |
+
return ret
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def openmx_parse_overlap(OLP_dir, output_dir):
|
| 66 |
+
assert os.path.exists(os.path.join(OLP_dir, "output", "overlaps_0.h5")), "No overlap files found"
|
| 67 |
+
assert os.path.exists(os.path.join(OLP_dir, "openmx.out")), "openmx.out not found"
|
| 68 |
+
|
| 69 |
+
overlaps = read_non_parallel_hdf5('overlaps', os.path.join(OLP_dir, 'output'))
|
| 70 |
+
assert len(overlaps.keys()) != 0, 'Can not found any overlap file'
|
| 71 |
+
fid = h5py.File(os.path.join(output_dir, 'overlaps.h5'), 'w')
|
| 72 |
+
for key_str, v in overlaps.items():
|
| 73 |
+
fid[key_str] = v
|
| 74 |
+
fid.close()
|
| 75 |
+
|
| 76 |
+
orbital2l = {"s": 0, "p": 1, "d": 2, "f": 3}
|
| 77 |
+
# parse openmx.out
|
| 78 |
+
with open(os.path.join(OLP_dir, "openmx.out"), "r") as f:
|
| 79 |
+
lines = f.readlines()
|
| 80 |
+
orbital_dict = {}
|
| 81 |
+
lattice = np.zeros((3, 3))
|
| 82 |
+
frac_coords = []
|
| 83 |
+
atomic_elements_str = []
|
| 84 |
+
flag_read_orbital = False
|
| 85 |
+
flag_read_lattice = False
|
| 86 |
+
for index_line, line in enumerate(lines):
|
| 87 |
+
if line.find('Definition.of.Atomic.Species>') != -1:
|
| 88 |
+
flag_read_orbital = False
|
| 89 |
+
if flag_read_orbital:
|
| 90 |
+
element = line.split()[0]
|
| 91 |
+
orbital_str = (line.split()[1]).split('-')[-1]
|
| 92 |
+
l_list = []
|
| 93 |
+
assert len(orbital_str) % 2 == 0
|
| 94 |
+
for index_str in range(len(orbital_str) // 2):
|
| 95 |
+
l_list.extend([orbital2l[orbital_str[index_str * 2]]] * int(orbital_str[index_str * 2 + 1]))
|
| 96 |
+
orbital_dict[element] = l_list
|
| 97 |
+
if line.find('<Definition.of.Atomic.Species') != -1:
|
| 98 |
+
flag_read_orbital = True
|
| 99 |
+
|
| 100 |
+
if line.find('Atoms.UnitVectors.Unit') != -1:
|
| 101 |
+
assert line.split()[1] == "Ang", "Unit of lattice vector is not Angstrom"
|
| 102 |
+
assert lines[index_line + 1].find("<Atoms.UnitVectors") != -1
|
| 103 |
+
lattice[0, :] = np.array(list(map(float, lines[index_line + 2].split())))
|
| 104 |
+
lattice[1, :] = np.array(list(map(float, lines[index_line + 3].split())))
|
| 105 |
+
lattice[2, :] = np.array(list(map(float, lines[index_line + 4].split())))
|
| 106 |
+
flag_read_lattice = True
|
| 107 |
+
|
| 108 |
+
if line.find('Fractional coordinates of the final structure') != -1:
|
| 109 |
+
index_atom = 0
|
| 110 |
+
while (index_line + index_atom + 4) < len(lines):
|
| 111 |
+
index_atom += 1
|
| 112 |
+
line_split = lines[index_line + index_atom + 3].split()
|
| 113 |
+
if len(line_split) == 0:
|
| 114 |
+
break
|
| 115 |
+
assert len(line_split) == 5
|
| 116 |
+
assert line_split[0] == str(index_atom)
|
| 117 |
+
atomic_elements_str.append(line_split[1])
|
| 118 |
+
frac_coords.append(np.array(list(map(float, line_split[2:]))))
|
| 119 |
+
print("Found", len(frac_coords), "atoms")
|
| 120 |
+
if flag_read_lattice is False:
|
| 121 |
+
raise RuntimeError("Could not find lattice vector in openmx.out")
|
| 122 |
+
if len(orbital_dict) == 0:
|
| 123 |
+
raise RuntimeError("Could not find orbital information in openmx.out")
|
| 124 |
+
frac_coords = np.array(frac_coords)
|
| 125 |
+
cart_coords = frac_coords @ lattice
|
| 126 |
+
|
| 127 |
+
np.savetxt(os.path.join(output_dir, "site_positions.dat"), cart_coords.T)
|
| 128 |
+
np.savetxt(os.path.join(output_dir, "lat.dat"), lattice.T)
|
| 129 |
+
np.savetxt(os.path.join(output_dir, "rlat.dat"), np.linalg.inv(lattice) * 2 * pi)
|
| 130 |
+
np.savetxt(os.path.join(output_dir, "element.dat"),
|
| 131 |
+
np.array(list(map(lambda x: periodic_table[x], atomic_elements_str))), fmt='%d')
|
| 132 |
+
with open(os.path.join(output_dir, 'orbital_types.dat'), 'w') as orbital_types_f:
|
| 133 |
+
for element_str in atomic_elements_str:
|
| 134 |
+
for index_l, l in enumerate(orbital_dict[element_str]):
|
| 135 |
+
if index_l == 0:
|
| 136 |
+
orbital_types_f.write(str(l))
|
| 137 |
+
else:
|
| 138 |
+
orbital_types_f.write(f" {l}")
|
| 139 |
+
orbital_types_f.write('\n')
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def read_non_parallel_hdf5(name, file_dir, num_p=256):
|
| 143 |
+
Os = {}
|
| 144 |
+
for index_p in range(num_p):
|
| 145 |
+
if os.path.exists(os.path.join(file_dir, f"{name}_{index_p}.h5")):
|
| 146 |
+
fid = h5py.File(os.path.join(file_dir, f"{name}_{index_p}.h5"), 'r')
|
| 147 |
+
for key_str, O_nm in fid.items():
|
| 148 |
+
Os[key_str] = O_nm[...]
|
| 149 |
+
assert not os.path.exists(os.path.join(file_dir, f"{name}_{num_p}.h5")), "Increase num_p because some overlap files are missing"
|
| 150 |
+
return Os
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def read_hdf5(name, file_dir):
|
| 154 |
+
Os = {}
|
| 155 |
+
fid = h5py.File(os.path.join(file_dir, f"{name}.h5"), 'r')
|
| 156 |
+
for key_str, O_nm in fid.items():
|
| 157 |
+
Os[key_str] = O_nm[...]
|
| 158 |
+
return Os
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class OijLoad:
|
| 162 |
+
def __init__(self, output_dir):
|
| 163 |
+
print("get data from:", output_dir)
|
| 164 |
+
self.if_load_scfout = False
|
| 165 |
+
self.output_dir = output_dir
|
| 166 |
+
term_non_parallel_list = ['H', 'T', 'V_xc', 'O_xc', 'O_dVHart', 'O_NA', 'O_NL', 'Rho']
|
| 167 |
+
self.term_h5_dict = {}
|
| 168 |
+
for term in term_non_parallel_list:
|
| 169 |
+
self.term_h5_dict[term] = read_non_parallel_hdf5(term, output_dir)
|
| 170 |
+
|
| 171 |
+
self.term_h5_dict['H_add'] = {}
|
| 172 |
+
for key_str in self.term_h5_dict['T'].keys():
|
| 173 |
+
tmp = np.zeros_like(self.term_h5_dict['T'][key_str])
|
| 174 |
+
for term in ['T', 'V_xc', 'O_dVHart', 'O_NA', 'O_NL']:
|
| 175 |
+
tmp += self.term_h5_dict[term][key_str]
|
| 176 |
+
self.term_h5_dict['H_add'][key_str] = tmp
|
| 177 |
+
|
| 178 |
+
self.dig_term = {}
|
| 179 |
+
for term in ['E_dVHart_a', 'E_xc_pcc']:
|
| 180 |
+
self.dig_term[term] = np.loadtxt(os.path.join(output_dir, f'{term}.dat'))
|
| 181 |
+
|
| 182 |
+
def cal_Eij(self):
|
| 183 |
+
term_list = ["E_kin", "E_NA", "E_NL", "E_delta_ee", "E_xc"]
|
| 184 |
+
self.Eij = {term: {} for term in term_list}
|
| 185 |
+
self.R_list = []
|
| 186 |
+
for key_str in self.term_h5_dict['T'].keys():
|
| 187 |
+
key = json.loads(key_str)
|
| 188 |
+
R = (key[0], key[1], key[2])
|
| 189 |
+
if R not in self.R_list:
|
| 190 |
+
self.R_list.append(R)
|
| 191 |
+
atom_i = key[3] - 1
|
| 192 |
+
atom_j = key[4] - 1
|
| 193 |
+
|
| 194 |
+
self.Eij["E_NA"][key_str] = (self.term_h5_dict["O_NA"][key_str] * self.term_h5_dict["Rho"][key_str]).sum() * 2
|
| 195 |
+
self.Eij["E_NL"][key_str] = (self.term_h5_dict["O_NL"][key_str] * self.term_h5_dict["Rho"][key_str]).sum() * 2
|
| 196 |
+
self.Eij["E_kin"][key_str] = (self.term_h5_dict["T"][key_str] * self.term_h5_dict["Rho"][key_str]).sum() * 2
|
| 197 |
+
self.Eij["E_delta_ee"][key_str] = (self.term_h5_dict["O_dVHart"][key_str] * self.term_h5_dict["Rho"][key_str]).sum()
|
| 198 |
+
self.Eij["E_xc"][key_str] = (self.term_h5_dict["O_xc"][key_str] * self.term_h5_dict["Rho"][key_str]).sum() * 2
|
| 199 |
+
if (atom_i == atom_j) and (R == (0, 0, 0)):
|
| 200 |
+
self.Eij["E_delta_ee"][key_str] -= self.dig_term['E_dVHart_a'][atom_i]
|
| 201 |
+
self.Eij["E_xc"][key_str] += self.dig_term['E_xc_pcc'][atom_i] * 2
|
| 202 |
+
|
| 203 |
+
def load_scfout(self):
|
| 204 |
+
self.if_load_scfout = True
|
| 205 |
+
term_list = ["hamiltonians", "overlaps", "density_matrixs"]
|
| 206 |
+
default_dtype = np.complex128
|
| 207 |
+
|
| 208 |
+
for term in term_list:
|
| 209 |
+
self.term_h5_dict[term] = read_hdf5(term, self.output_dir)
|
| 210 |
+
|
| 211 |
+
site_positions = np.loadtxt(os.path.join(self.output_dir, 'site_positions.dat')).T
|
| 212 |
+
self.lat = np.loadtxt(os.path.join(self.output_dir, 'lat.dat')).T
|
| 213 |
+
self.rlat = np.loadtxt(os.path.join(self.output_dir, 'rlat.dat')).T
|
| 214 |
+
nsites = site_positions.shape[0]
|
| 215 |
+
|
| 216 |
+
self.orbital_types = []
|
| 217 |
+
with open(os.path.join(self.output_dir, 'orbital_types.dat'), 'r') as orbital_types_f:
|
| 218 |
+
for index_site in range(nsites):
|
| 219 |
+
self.orbital_types.append(np.array(list(map(int, orbital_types_f.readline().split()))))
|
| 220 |
+
site_norbits = list(map(lambda x: (2 * x + 1).sum(), self.orbital_types))
|
| 221 |
+
site_norbits_cumsum = np.cumsum(site_norbits)
|
| 222 |
+
norbits = sum(site_norbits)
|
| 223 |
+
|
| 224 |
+
self.term_R_dict = {term: {} for term in self.term_h5_dict.keys()}
|
| 225 |
+
for key_str in tqdm.tqdm(self.term_h5_dict['overlaps'].keys()):
|
| 226 |
+
key = json.loads(key_str)
|
| 227 |
+
R = (key[0], key[1], key[2])
|
| 228 |
+
atom_i = key[3] - 1
|
| 229 |
+
atom_j = key[4] - 1
|
| 230 |
+
if R not in self.term_R_dict['overlaps']:
|
| 231 |
+
for term_R in self.term_R_dict.values():
|
| 232 |
+
term_R[R] = np.zeros((norbits, norbits), dtype=default_dtype)
|
| 233 |
+
matrix_slice_i = slice(site_norbits_cumsum[atom_i] - site_norbits[atom_i], site_norbits_cumsum[atom_i])
|
| 234 |
+
matrix_slice_j = slice(site_norbits_cumsum[atom_j] - site_norbits[atom_j], site_norbits_cumsum[atom_j])
|
| 235 |
+
for term, term_R in self.term_R_dict.items():
|
| 236 |
+
term_R[R][matrix_slice_i, matrix_slice_j] = np.array(self.term_h5_dict[term][key_str]).astype(
|
| 237 |
+
dtype=default_dtype)
|
| 238 |
+
|
| 239 |
+
def get_E_band(self):
|
| 240 |
+
E_band = 0.0
|
| 241 |
+
for R in self.term_R_dict['T'].keys():
|
| 242 |
+
E_band += (self.term_R_dict['density_matrixs'][R] * self.term_R_dict['H_add'][R]).sum()
|
| 243 |
+
return E_band
|
| 244 |
+
|
| 245 |
+
def get_E_band2(self):
|
| 246 |
+
E_band = 0.0
|
| 247 |
+
for R in self.term_R_dict['T'].keys():
|
| 248 |
+
E_band += (self.term_R_dict['density_matrixs'][R] * self.term_R_dict['hamiltonians'][R]).sum()
|
| 249 |
+
return E_band
|
| 250 |
+
|
| 251 |
+
def get_E_band3(self):
|
| 252 |
+
E_band = 0.0
|
| 253 |
+
for R in self.term_R_dict['T'].keys():
|
| 254 |
+
E_band += (self.term_R_dict['density_matrixs'][R] * self.term_R_dict['H'][R]).sum()
|
| 255 |
+
return E_band
|
| 256 |
+
|
| 257 |
+
def sum_Eij(self, term):
|
| 258 |
+
ret = 0.0
|
| 259 |
+
for value in self.Eij[term].values():
|
| 260 |
+
ret += value
|
| 261 |
+
return ret
|
| 262 |
+
|
| 263 |
+
def get_E_NL(self):
|
| 264 |
+
assert self.if_load_scfout == True
|
| 265 |
+
E_NL = 0.0
|
| 266 |
+
for R in self.term_R_dict['T'].keys():
|
| 267 |
+
E_NL += (self.term_R_dict['density_matrixs'][R] * self.term_R_dict['O_NL'][R]).sum()
|
| 268 |
+
return E_NL
|
| 269 |
+
|
| 270 |
+
def save_Vij(self, save_dir):
|
| 271 |
+
for term, h5_file_name in zip(["O_NA", "O_dVHart", "V_xc", "H_add", "Rho"],
|
| 272 |
+
["V_nas", "V_delta_ees", "V_xcs", "hamiltonians", "density_matrixs"]):
|
| 273 |
+
fid = h5py.File(os.path.join(save_dir, f'{h5_file_name}.h5'), "w")
|
| 274 |
+
for k, v in self.term_h5_dict[term].items():
|
| 275 |
+
fid[k] = v
|
| 276 |
+
fid.close()
|
| 277 |
+
|
| 278 |
+
def get_E5ij(self):
|
| 279 |
+
term_list = ["E_kin", "E_NA", "E_NL", "E_delta_ee", "E_xc"]
|
| 280 |
+
E_dict = {term: 0 for term in term_list}
|
| 281 |
+
E5ij = {}
|
| 282 |
+
for key_str in self.Eij[term_list[0]].keys():
|
| 283 |
+
tmp = 0.0
|
| 284 |
+
for term in term_list:
|
| 285 |
+
v = self.Eij[term][key_str]
|
| 286 |
+
E_dict[term] += v
|
| 287 |
+
tmp += v
|
| 288 |
+
if key_str in E5ij:
|
| 289 |
+
E5ij[key_str] += tmp
|
| 290 |
+
else:
|
| 291 |
+
E5ij[key_str] = tmp
|
| 292 |
+
return E5ij, E_dict
|
| 293 |
+
|
| 294 |
+
def save_Eij(self, save_dir):
|
| 295 |
+
fid_tmp, E_dict = self.get_E5ij()
|
| 296 |
+
|
| 297 |
+
fid = h5py.File(os.path.join(save_dir, f'E_ij.h5'), "w")
|
| 298 |
+
for k, v in fid_tmp.items():
|
| 299 |
+
fid[k] = v
|
| 300 |
+
fid.close()
|
| 301 |
+
|
| 302 |
+
with open(os.path.join(save_dir, "openmx_E_ij_E.json"), 'w') as E_file:
|
| 303 |
+
json.dump({
|
| 304 |
+
"E_kin": E_dict["E_kin"],
|
| 305 |
+
"E_delta_ee": E_dict["E_delta_ee"],
|
| 306 |
+
"E_NA": E_dict["E_NA"],
|
| 307 |
+
"E_NL": E_dict["E_NL"],
|
| 308 |
+
"E_xc": E_dict["E_xc"]
|
| 309 |
+
}, E_file)
|
| 310 |
+
|
| 311 |
+
# return E_dict["E_delta_ee"], E_dict["E_xc"]
|
| 312 |
+
return E_dict["E_kin"], E_dict["E_delta_ee"], E_dict["E_NA"], E_dict["E_NL"], E_dict["E_xc"]
|
| 313 |
+
|
| 314 |
+
def get_E5i(self):
|
| 315 |
+
term_list = ["E_kin", "E_NA", "E_NL", "E_delta_ee", "E_xc"]
|
| 316 |
+
E_dict = {term: 0 for term in term_list}
|
| 317 |
+
E5i = {}
|
| 318 |
+
for key_str in self.Eij[term_list[0]].keys():
|
| 319 |
+
key = json.loads(key_str)
|
| 320 |
+
atom_i_str = str(key[3] - 1)
|
| 321 |
+
tmp = 0.0
|
| 322 |
+
for term in term_list:
|
| 323 |
+
v = self.Eij[term][key_str]
|
| 324 |
+
E_dict[term] += v
|
| 325 |
+
tmp += v
|
| 326 |
+
if atom_i_str in E5i:
|
| 327 |
+
E5i[atom_i_str] += tmp
|
| 328 |
+
else:
|
| 329 |
+
E5i[atom_i_str] = tmp
|
| 330 |
+
return E5i, E_dict
|
| 331 |
+
|
| 332 |
+
def save_Ei(self, save_dir):
|
| 333 |
+
fid_tmp, E_dict = self.get_E5i()
|
| 334 |
+
|
| 335 |
+
fid = h5py.File(os.path.join(save_dir, f'E_i.h5'), "w")
|
| 336 |
+
for k, v in fid_tmp.items():
|
| 337 |
+
fid[k] = v
|
| 338 |
+
fid.close()
|
| 339 |
+
with open(os.path.join(save_dir, "openmx_E_i_E.json"), 'w') as E_file:
|
| 340 |
+
json.dump({
|
| 341 |
+
"E_kin": E_dict["E_kin"],
|
| 342 |
+
"E_delta_ee": E_dict["E_delta_ee"],
|
| 343 |
+
"E_NA": E_dict["E_NA"],
|
| 344 |
+
"E_NL": E_dict["E_NL"],
|
| 345 |
+
"E_xc": E_dict["E_xc"]
|
| 346 |
+
}, E_file)
|
| 347 |
+
return E_dict["E_kin"], E_dict["E_delta_ee"], E_dict["E_NA"], E_dict["E_NL"], E_dict["E_xc"]
|
| 348 |
+
|
| 349 |
+
def get_R_list(self):
|
| 350 |
+
return self.R_list
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
class GetEEiEij:
|
| 354 |
+
def __init__(self, input_dir):
|
| 355 |
+
self.load_kernel = OijLoad(os.path.join(input_dir, "output"))
|
| 356 |
+
self.E_kin, self.E_delta_ee, self.E_NA, self.E_NL, self.E_xc, self.Etot, self.force = openmx_force_intferface(
|
| 357 |
+
os.path.join(input_dir, "openmx.out"), save_dir=None, return_Etot=True, return_force=True)
|
| 358 |
+
self.load_kernel.cal_Eij()
|
| 359 |
+
|
| 360 |
+
def get_Etot(self):
|
| 361 |
+
# unit: kcal mol^-1
|
| 362 |
+
return self.Etot * Ev2Kcalmol
|
| 363 |
+
|
| 364 |
+
def get_force(self):
|
| 365 |
+
# unit: kcal mol^-1 Angstrom^-1
|
| 366 |
+
return self.force * Ev2Kcalmol
|
| 367 |
+
|
| 368 |
+
def get_E5(self):
|
| 369 |
+
# unit: kcal mol^-1
|
| 370 |
+
return (self.E_kin + self.E_delta_ee + self.E_NA + self.E_NL + self.E_xc) * Ev2Kcalmol
|
| 371 |
+
|
| 372 |
+
def get_E5i(self):
|
| 373 |
+
# unit: kcal mol^-1
|
| 374 |
+
E5i, E_from_i_dict = self.load_kernel.get_E5i()
|
| 375 |
+
assert np.allclose(self.E_kin, E_from_i_dict["E_kin"])
|
| 376 |
+
assert np.allclose(self.E_delta_ee, E_from_i_dict["E_delta_ee"])
|
| 377 |
+
assert np.allclose(self.E_NA, E_from_i_dict["E_NA"])
|
| 378 |
+
assert np.allclose(self.E_NL, E_from_i_dict["E_NL"])
|
| 379 |
+
assert np.allclose(self.E_xc, E_from_i_dict["E_xc"], rtol=1.e-3)
|
| 380 |
+
return {k: v * Ev2Kcalmol for k, v in E5i.items()}
|
| 381 |
+
|
| 382 |
+
def get_E5ij(self):
|
| 383 |
+
# unit: kcal mol^-1
|
| 384 |
+
E5ij, E_from_ij_dict = self.load_kernel.get_E5ij()
|
| 385 |
+
assert np.allclose(self.E_kin, E_from_ij_dict["E_kin"])
|
| 386 |
+
assert np.allclose(self.E_delta_ee, E_from_ij_dict["E_delta_ee"])
|
| 387 |
+
assert np.allclose(self.E_NA, E_from_ij_dict["E_NA"])
|
| 388 |
+
assert np.allclose(self.E_NL, E_from_ij_dict["E_NL"])
|
| 389 |
+
assert np.allclose(self.E_xc, E_from_ij_dict["E_xc"], rtol=1.e-3)
|
| 390 |
+
return {k: v * Ev2Kcalmol for k, v in E5ij.items()}
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
if __name__ == '__main__':
|
| 394 |
+
parser = argparse.ArgumentParser(description='Predict Hamiltonian')
|
| 395 |
+
parser.add_argument(
|
| 396 |
+
'--input_dir', type=str, default='./',
|
| 397 |
+
help='path of openmx.out, and output'
|
| 398 |
+
)
|
| 399 |
+
parser.add_argument(
|
| 400 |
+
'--output_dir', type=str, default='./',
|
| 401 |
+
help='path of output E_xc_ij.h5, E_delta_ee_ij.h5, site_positions.dat, lat.dat, element.dat, and R_list.dat'
|
| 402 |
+
)
|
| 403 |
+
parser.add_argument('--Ei', action='store_true')
|
| 404 |
+
parser.add_argument('--stru_dir', type=str, default='POSCAR', help='path of structure file')
|
| 405 |
+
args = parser.parse_args()
|
| 406 |
+
|
| 407 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 408 |
+
load_kernel = OijLoad(os.path.join(args.input_dir, "output"))
|
| 409 |
+
E_kin, E_delta_ee, E_NA, E_NL, E_xc = openmx_force_intferface(os.path.join(args.input_dir, "openmx.out"), args.output_dir)
|
| 410 |
+
load_kernel.cal_Eij()
|
| 411 |
+
if args.Ei:
|
| 412 |
+
E_kin_from_ij, E_delta_ee_from_ij, E_NA_from_ij, E_NL_from_ij, E_xc_from_ij = load_kernel.save_Ei(args.output_dir)
|
| 413 |
+
else:
|
| 414 |
+
E_kin_from_ij, E_delta_ee_from_ij, E_NA_from_ij, E_NL_from_ij, E_xc_from_ij = load_kernel.save_Eij(args.output_dir)
|
| 415 |
+
assert np.allclose(E_kin, E_kin_from_ij)
|
| 416 |
+
assert np.allclose(E_delta_ee, E_delta_ee_from_ij)
|
| 417 |
+
assert np.allclose(E_NA, E_NA_from_ij)
|
| 418 |
+
assert np.allclose(E_NL, E_NL_from_ij)
|
| 419 |
+
assert np.allclose(E_xc, E_xc_from_ij, rtol=1.e-3)
|
| 420 |
+
|
| 421 |
+
structure = Structure.from_file(args.stru_dir)
|
| 422 |
+
np.savetxt(os.path.join(args.output_dir, "site_positions.dat"), structure.cart_coords.T)
|
| 423 |
+
np.savetxt(os.path.join(args.output_dir, "lat.dat"), structure.lattice.matrix.T)
|
| 424 |
+
np.savetxt(os.path.join(args.output_dir, "element.dat"), structure.atomic_numbers, fmt='%d')
|
| 425 |
+
np.savetxt(os.path.join(args.output_dir, "R_list.dat"), load_kernel.get_R_list(), fmt='%d')
|
2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/preprocess/periodic_table.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/preprocess/preprocess_default.ini
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[basic]
|
| 2 |
+
raw_dir = /your/own/path
|
| 3 |
+
processed_dir = /your/own/path
|
| 4 |
+
target = hamiltonian
|
| 5 |
+
interface = openmx
|
| 6 |
+
multiprocessing = 0
|
| 7 |
+
local_coordinate = True
|
| 8 |
+
get_S = False
|
| 9 |
+
|
| 10 |
+
[interpreter]
|
| 11 |
+
julia_interpreter = julia
|
| 12 |
+
|
| 13 |
+
[graph]
|
| 14 |
+
radius = -1.0
|
| 15 |
+
create_from_DFT = True
|
| 16 |
+
r2_rand = False
|
| 17 |
+
|
| 18 |
+
[magnetic_moment]
|
| 19 |
+
parse_magnetic_moment = False
|
| 20 |
+
magnetic_element = ["Cr", "Mn", "Fe", "Co", "Ni"]
|
2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/preprocess/siesta_get_data.py
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import numpy as np
|
| 3 |
+
from numpy.core.fromnumeric import sort
|
| 4 |
+
import scipy as sp
|
| 5 |
+
import h5py
|
| 6 |
+
import json
|
| 7 |
+
from scipy.io import FortranFile
|
| 8 |
+
|
| 9 |
+
# Transfer SIESTA output to DeepH format
|
| 10 |
+
# DeepH-pack: https://deeph-pack.readthedocs.io/en/latest/index.html
|
| 11 |
+
# Coded by ZC Tang @ Tsinghua Univ. e-mail: az_txycha@126.com
|
| 12 |
+
|
| 13 |
+
def siesta_parse(input_path, output_path):
|
| 14 |
+
input_path = os.path.abspath(input_path)
|
| 15 |
+
output_path = os.path.abspath(output_path)
|
| 16 |
+
os.makedirs(output_path, exist_ok=True)
|
| 17 |
+
|
| 18 |
+
# finds system name
|
| 19 |
+
f_list = os.listdir(input_path)
|
| 20 |
+
for f_name in f_list:
|
| 21 |
+
if f_name[::-1][0:9] == 'XDNI_BRO.':
|
| 22 |
+
system_name = f_name[:-9]
|
| 23 |
+
|
| 24 |
+
with open('{}/{}.STRUCT_OUT'.format(input_path,system_name), 'r') as struct: # structure info from standard output
|
| 25 |
+
lattice = np.empty((3,3))
|
| 26 |
+
for i in range(3):
|
| 27 |
+
line = struct.readline()
|
| 28 |
+
linesplit = line.split()
|
| 29 |
+
lattice[i,:] = linesplit[:]
|
| 30 |
+
np.savetxt('{}/lat.dat'.format(output_path), np.transpose(lattice), fmt='%.18e')
|
| 31 |
+
line = struct.readline()
|
| 32 |
+
linesplit = line.split()
|
| 33 |
+
num_atoms = int(linesplit[0])
|
| 34 |
+
atom_coord = np.empty((num_atoms, 4))
|
| 35 |
+
for i in range(num_atoms):
|
| 36 |
+
line = struct.readline()
|
| 37 |
+
linesplit = line.split()
|
| 38 |
+
atom_coord[i, :] = linesplit[1:]
|
| 39 |
+
np.savetxt('{}/element.dat'.format(output_path), atom_coord[:,0], fmt='%d')
|
| 40 |
+
|
| 41 |
+
atom_coord_cart = np.genfromtxt('{}/{}.XV'.format(input_path,system_name),skip_header = 4)
|
| 42 |
+
atom_coord_cart = atom_coord_cart[:,2:5] * 0.529177249
|
| 43 |
+
np.savetxt('{}/site_positions.dat'.format(output_path), np.transpose(atom_coord_cart))
|
| 44 |
+
|
| 45 |
+
orb_indx = np.genfromtxt('{}/{}.ORB_INDX'.format(input_path,system_name), skip_header=3, skip_footer=17)
|
| 46 |
+
# orb_indx rows: 0 orbital id 1 atom id 2 atom type 3 element symbol
|
| 47 |
+
# 4 orbital id within atom 5 n 6 l
|
| 48 |
+
# 7 m 8 zeta 9 Polarized? 10 orbital symmetry
|
| 49 |
+
# 11 rc(a.u.) 12-14 R 15 equivalent orbital index in uc
|
| 50 |
+
|
| 51 |
+
orb_indx[:,12:15]=orb_indx[:,12:15]
|
| 52 |
+
|
| 53 |
+
with open('{}/R_list.dat'.format(output_path),'w') as R_list_f:
|
| 54 |
+
R_prev = np.empty(3)
|
| 55 |
+
for i in range(len(orb_indx)):
|
| 56 |
+
R = orb_indx[i, 12:15]
|
| 57 |
+
if (R != R_prev).any():
|
| 58 |
+
R_prev = R
|
| 59 |
+
R_list_f.write('{} {} {}\n'.format(int(R[0]), int(R[1]), int(R[2])))
|
| 60 |
+
|
| 61 |
+
ia2Riua = np.empty((0,4)) #DeepH key
|
| 62 |
+
ia = 0
|
| 63 |
+
for i in range(len(orb_indx)):
|
| 64 |
+
if orb_indx[i][1] != ia:
|
| 65 |
+
ia = orb_indx[i][1]
|
| 66 |
+
Riua = np.empty((1,4))
|
| 67 |
+
Riua[0,0:3] = orb_indx[i][12:15]
|
| 68 |
+
iuo = int(orb_indx[i][15])
|
| 69 |
+
iua = int(orb_indx[iuo-1,1])
|
| 70 |
+
Riua[0,3] = int(iua)
|
| 71 |
+
ia2Riua = np.append(ia2Riua, Riua)
|
| 72 |
+
ia2Riua = ia2Riua.reshape(int(len(ia2Riua)/4),4)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
#hamiltonians.h5, density_matrixs.h5, overlap.h5
|
| 76 |
+
info = {'nsites' : num_atoms, 'isorthogonal': False, 'isspinful': False, 'norbits': len(orb_indx)}
|
| 77 |
+
with open('{}/info.json'.format(output_path), 'w') as info_f:
|
| 78 |
+
json.dump(info, info_f)
|
| 79 |
+
|
| 80 |
+
a1 = lattice[0, :]
|
| 81 |
+
a2 = lattice[1, :]
|
| 82 |
+
a3 = lattice[2, :]
|
| 83 |
+
b1 = 2 * np.pi * np.cross(a2, a3) / (np.dot(a1, np.cross(a2, a3)))
|
| 84 |
+
b2 = 2 * np.pi * np.cross(a3, a1) / (np.dot(a2, np.cross(a3, a1)))
|
| 85 |
+
b3 = 2 * np.pi * np.cross(a1, a2) / (np.dot(a3, np.cross(a1, a2)))
|
| 86 |
+
rlattice = np.array([b1, b2, b3])
|
| 87 |
+
np.savetxt('{}/rlat.dat'.format(output_path), np.transpose(rlattice), fmt='%.18e')
|
| 88 |
+
|
| 89 |
+
# Cope with orbital type information
|
| 90 |
+
i = 0
|
| 91 |
+
with open('{}/orbital_types.dat'.format(output_path), 'w') as orb_type_f:
|
| 92 |
+
atom_current = 0
|
| 93 |
+
while True: # Loop over atoms in unitcell
|
| 94 |
+
if atom_current != orb_indx[i, 1]:
|
| 95 |
+
if atom_current != 0:
|
| 96 |
+
for j in range(4):
|
| 97 |
+
for _ in range(int(atom_orb_cnt[j]/(2*j+1))):
|
| 98 |
+
orb_type_f.write('{} '.format(j))
|
| 99 |
+
orb_type_f.write('\n')
|
| 100 |
+
|
| 101 |
+
atom_current = int(orb_indx[i, 1])
|
| 102 |
+
atom_orb_cnt = np.array([0,0,0,0]) # number of s, p, d, f orbitals in specific atom
|
| 103 |
+
l = int(orb_indx[i, 6])
|
| 104 |
+
atom_orb_cnt[l] += 1
|
| 105 |
+
i += 1
|
| 106 |
+
if i > len(orb_indx)-1:
|
| 107 |
+
for j in range(4):
|
| 108 |
+
for _ in range(int(atom_orb_cnt[j]/(2*j+1))):
|
| 109 |
+
orb_type_f.write('{} '.format(j))
|
| 110 |
+
orb_type_f.write('\n')
|
| 111 |
+
break
|
| 112 |
+
if orb_indx[i, 0] != orb_indx[i, 15]:
|
| 113 |
+
for j in range(4):
|
| 114 |
+
for _ in range(int(atom_orb_cnt[j]/(2*j+1))):
|
| 115 |
+
orb_type_f.write('{} '.format(j))
|
| 116 |
+
orb_type_f.write('\n')
|
| 117 |
+
break
|
| 118 |
+
|
| 119 |
+
# yields key for *.h5 file
|
| 120 |
+
orb2deephorb = np.zeros((len(orb_indx), 5))
|
| 121 |
+
atom_current = 1
|
| 122 |
+
orb_atom_current = np.empty((0)) # stores orbitals' id in siesta, n, l, m and z, will be reshaped into orb*5
|
| 123 |
+
t = 0
|
| 124 |
+
for i in range(len(orb_indx)):
|
| 125 |
+
orb_atom_current = np.append(orb_atom_current, i)
|
| 126 |
+
orb_atom_current = np.append(orb_atom_current, orb_indx[i,5:9])
|
| 127 |
+
if i != len(orb_indx)-1 :
|
| 128 |
+
if orb_indx[i+1,1] != atom_current:
|
| 129 |
+
orb_atom_current = np.reshape(orb_atom_current,((int(len(orb_atom_current)/5),5)))
|
| 130 |
+
for j in range(len(orb_atom_current)):
|
| 131 |
+
if orb_atom_current[j,2] == 1: #p
|
| 132 |
+
if orb_atom_current[j,3] == -1:
|
| 133 |
+
orb_atom_current[j,3] = 0
|
| 134 |
+
elif orb_atom_current[j,3] == 0:
|
| 135 |
+
orb_atom_current[j,3] = 1
|
| 136 |
+
elif orb_atom_current[j,3] == 1:
|
| 137 |
+
orb_atom_current[j,3] = -1
|
| 138 |
+
if orb_atom_current[j,2] == 2: #d
|
| 139 |
+
if orb_atom_current[j,3] == -2:
|
| 140 |
+
orb_atom_current[j,3] = 0
|
| 141 |
+
elif orb_atom_current[j,3] == -1:
|
| 142 |
+
orb_atom_current[j,3] = 2
|
| 143 |
+
elif orb_atom_current[j,3] == 0:
|
| 144 |
+
orb_atom_current[j,3] = -2
|
| 145 |
+
elif orb_atom_current[j,3] == 1:
|
| 146 |
+
orb_atom_current[j,3] = 1
|
| 147 |
+
elif orb_atom_current[j,3] == 2:
|
| 148 |
+
orb_atom_current[j,3] = -1
|
| 149 |
+
if orb_atom_current[j,2] == 3: #f
|
| 150 |
+
if orb_atom_current[j,3] == -3:
|
| 151 |
+
orb_atom_current[j,3] = 0
|
| 152 |
+
elif orb_atom_current[j,3] == -2:
|
| 153 |
+
orb_atom_current[j,3] = 1
|
| 154 |
+
elif orb_atom_current[j,3] == -1:
|
| 155 |
+
orb_atom_current[j,3] = -1
|
| 156 |
+
elif orb_atom_current[j,3] == 0:
|
| 157 |
+
orb_atom_current[j,3] = 2
|
| 158 |
+
elif orb_atom_current[j,3] == 1:
|
| 159 |
+
orb_atom_current[j,3] = -2
|
| 160 |
+
elif orb_atom_current[j,3] == 2:
|
| 161 |
+
orb_atom_current[j,3] = 3
|
| 162 |
+
elif orb_atom_current[j,3] == 3:
|
| 163 |
+
orb_atom_current[j,3] = -3
|
| 164 |
+
sort_index = np.zeros(len(orb_atom_current))
|
| 165 |
+
for j in range(len(orb_atom_current)):
|
| 166 |
+
sort_index[j] = orb_atom_current[j,3] + 10 * orb_atom_current[j,4] + 100 * orb_atom_current[j,1] + 1000 * orb_atom_current[j,2]
|
| 167 |
+
orb_order = np.argsort(sort_index)
|
| 168 |
+
tmpt = np.empty(len(orb_order))
|
| 169 |
+
for j in range(len(orb_order)):
|
| 170 |
+
tmpt[orb_order[j]] = j
|
| 171 |
+
orb_order = tmpt
|
| 172 |
+
for j in range(len(orb_atom_current)):
|
| 173 |
+
orb2deephorb[t,0:3] = np.round(orb_indx[t,12:15])
|
| 174 |
+
orb2deephorb[t,3] = ia2Riua[int(orb_indx[t,1])-1,3]
|
| 175 |
+
orb2deephorb[t,4] = int(orb_order[j])
|
| 176 |
+
t += 1
|
| 177 |
+
atom_current += 1
|
| 178 |
+
orb_atom_current = np.empty((0))
|
| 179 |
+
|
| 180 |
+
orb_atom_current = np.reshape(orb_atom_current,((int(len(orb_atom_current)/5),5)))
|
| 181 |
+
for j in range(len(orb_atom_current)):
|
| 182 |
+
if orb_atom_current[j,2] == 1:
|
| 183 |
+
if orb_atom_current[j,3] == -1:
|
| 184 |
+
orb_atom_current[j,3] = 0
|
| 185 |
+
elif orb_atom_current[j,3] == 0:
|
| 186 |
+
orb_atom_current[j,3] = 1
|
| 187 |
+
elif orb_atom_current[j,3] == 1:
|
| 188 |
+
orb_atom_current[j,3] = -1
|
| 189 |
+
if orb_atom_current[j,2] == 2:
|
| 190 |
+
if orb_atom_current[j,3] == -2:
|
| 191 |
+
orb_atom_current[j,3] = 0
|
| 192 |
+
elif orb_atom_current[j,3] == -1:
|
| 193 |
+
orb_atom_current[j,3] = 2
|
| 194 |
+
elif orb_atom_current[j,3] == 0:
|
| 195 |
+
orb_atom_current[j,3] = -2
|
| 196 |
+
elif orb_atom_current[j,3] == 1:
|
| 197 |
+
orb_atom_current[j,3] = 1
|
| 198 |
+
elif orb_atom_current[j,3] == 2:
|
| 199 |
+
orb_atom_current[j,3] = -1
|
| 200 |
+
if orb_atom_current[j,2] == 3: #f
|
| 201 |
+
if orb_atom_current[j,3] == -3:
|
| 202 |
+
orb_atom_current[j,3] = 0
|
| 203 |
+
elif orb_atom_current[j,3] == -2:
|
| 204 |
+
orb_atom_current[j,3] = 1
|
| 205 |
+
elif orb_atom_current[j,3] == -1:
|
| 206 |
+
orb_atom_current[j,3] = -1
|
| 207 |
+
elif orb_atom_current[j,3] == 0:
|
| 208 |
+
orb_atom_current[j,3] = 2
|
| 209 |
+
elif orb_atom_current[j,3] == 1:
|
| 210 |
+
orb_atom_current[j,3] = -2
|
| 211 |
+
elif orb_atom_current[j,3] == 2:
|
| 212 |
+
orb_atom_current[j,3] = 3
|
| 213 |
+
elif orb_atom_current[j,3] == 3:
|
| 214 |
+
orb_atom_current[j,3] = -3
|
| 215 |
+
sort_index = np.zeros(len(orb_atom_current))
|
| 216 |
+
for j in range(len(orb_atom_current)):
|
| 217 |
+
sort_index[j] = orb_atom_current[j,3] + 10 * orb_atom_current[j,4] + 100 * orb_atom_current[j,1] + 1000 * orb_atom_current[j,2]
|
| 218 |
+
orb_order = np.argsort(sort_index)
|
| 219 |
+
tmpt = np.empty(len(orb_order))
|
| 220 |
+
for j in range(len(orb_order)):
|
| 221 |
+
tmpt[orb_order[j]] = j
|
| 222 |
+
orb_order = tmpt
|
| 223 |
+
for j in range(len(orb_atom_current)):
|
| 224 |
+
orb2deephorb[t,0:3] = np.round(orb_indx[t,12:15])
|
| 225 |
+
orb2deephorb[t,3] = ia2Riua[int(orb_indx[t,1])-1,3]
|
| 226 |
+
orb2deephorb[t,4] = int(orb_order[j])
|
| 227 |
+
t += 1
|
| 228 |
+
|
| 229 |
+
# Read Useful info of HSX, We only need H and S from this file, but due to structure of fortran unformatted, extra information must be read
|
| 230 |
+
f = FortranFile('{}/{}.HSX'.format(input_path,system_name), 'r')
|
| 231 |
+
tmpt = f.read_ints() # no_u, no_s, nspin, nh
|
| 232 |
+
no_u = tmpt[0]
|
| 233 |
+
no_s = tmpt[1]
|
| 234 |
+
nspin = tmpt[2]
|
| 235 |
+
nh = tmpt[3]
|
| 236 |
+
tmpt = f.read_ints() # gamma
|
| 237 |
+
tmpt = f.read_ints() # indxuo
|
| 238 |
+
tmpt = f.read_ints() # numh
|
| 239 |
+
maxnumh = max(tmpt)
|
| 240 |
+
listh = np.zeros((no_u, maxnumh),dtype=int)
|
| 241 |
+
for i in range(no_u):
|
| 242 |
+
tmpt=f.read_ints() # listh
|
| 243 |
+
for j in range(len(tmpt)):
|
| 244 |
+
listh[i,j] = tmpt[j]
|
| 245 |
+
|
| 246 |
+
# finds set of connected atoms
|
| 247 |
+
connected_atoms = set()
|
| 248 |
+
for i in range(no_u):
|
| 249 |
+
for j in range(maxnumh):
|
| 250 |
+
if listh[i,j] == 0:
|
| 251 |
+
#print(j)
|
| 252 |
+
break
|
| 253 |
+
else:
|
| 254 |
+
atom_1 = int(orb2deephorb[i,3])#orbit i belongs to atom_1
|
| 255 |
+
atom_2 = int(orb2deephorb[listh[i,j]-1,3])# orbit j belongs to atom_2
|
| 256 |
+
Rijk = orb2deephorb[listh[i,j]-1,0:3]
|
| 257 |
+
Rijk = Rijk.astype(int)
|
| 258 |
+
connected_atoms = connected_atoms | set(['[{}, {}, {}, {}, {}]'.format(Rijk[0],Rijk[1],Rijk[2],atom_1,atom_2)])
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
H_block_sparse = dict()
|
| 262 |
+
for atom_pair in connected_atoms:
|
| 263 |
+
H_block_sparse[atom_pair] = []
|
| 264 |
+
# converts csr-like matrix into coo form in atomic pairs
|
| 265 |
+
for i in range(nspin):
|
| 266 |
+
for j in range(no_u):
|
| 267 |
+
tmpt=f.read_reals(dtype='<f4') # Hamiltonian
|
| 268 |
+
for k in range(len(tmpt)):
|
| 269 |
+
m = 0 # several orbits in siesta differs with DeepH in a (-1) factor
|
| 270 |
+
i2 = j
|
| 271 |
+
j2 = k
|
| 272 |
+
atom_1 = int(orb2deephorb[i2,3])
|
| 273 |
+
m += orb_indx[i2,7]
|
| 274 |
+
atom_2 = int(orb2deephorb[listh[i2,j2]-1,3])
|
| 275 |
+
m += orb_indx[listh[i2,j2]-1,7]
|
| 276 |
+
Rijk = orb2deephorb[listh[i2,j2]-1,0:3]
|
| 277 |
+
Rijk = Rijk.astype(int)
|
| 278 |
+
H_block_sparse['[{}, {}, {}, {}, {}]'.format(Rijk[0],Rijk[1],Rijk[2],atom_1,atom_2)].append([int(orb2deephorb[i2,4]),int(orb2deephorb[listh[i2,j2]-1,4]),tmpt[k]*((-1)**m)])
|
| 279 |
+
pass
|
| 280 |
+
|
| 281 |
+
S_block_sparse = dict()
|
| 282 |
+
for atom_pair in connected_atoms:
|
| 283 |
+
S_block_sparse[atom_pair] = []
|
| 284 |
+
|
| 285 |
+
for j in range(no_u):
|
| 286 |
+
tmpt=f.read_reals(dtype='<f4') # Overlap
|
| 287 |
+
for k in range(len(tmpt)):
|
| 288 |
+
m = 0
|
| 289 |
+
i2 = j
|
| 290 |
+
j2 = k
|
| 291 |
+
atom_1 = int(orb2deephorb[i2,3])
|
| 292 |
+
m += orb_indx[i2,7]
|
| 293 |
+
atom_2 = int(orb2deephorb[listh[i2,j2]-1,3])
|
| 294 |
+
m += orb_indx[listh[i2,j2]-1,7]
|
| 295 |
+
Rijk = orb2deephorb[listh[i2,j2]-1,0:3]
|
| 296 |
+
Rijk = Rijk.astype(int)
|
| 297 |
+
S_block_sparse['[{}, {}, {}, {}, {}]'.format(Rijk[0],Rijk[1],Rijk[2],atom_1,atom_2)].append([int(orb2deephorb[i2,4]),int(orb2deephorb[listh[i2,j2]-1,4]),tmpt[k]*((-1)**m)])
|
| 298 |
+
pass
|
| 299 |
+
pass
|
| 300 |
+
|
| 301 |
+
# finds number of orbitals of each atoms
|
| 302 |
+
nua = int(max(orb2deephorb[:,3]))
|
| 303 |
+
atom2nu = np.zeros(nua)
|
| 304 |
+
for i in range(len(orb_indx)):
|
| 305 |
+
if orb_indx[i,12]==0 and orb_indx[i,13]==0 and orb_indx[i,14]==0:
|
| 306 |
+
if orb_indx[i,4] > atom2nu[int(orb_indx[i,1])-1]:
|
| 307 |
+
atom2nu[int(orb_indx[i,1]-1)] = int(orb_indx[i,4])
|
| 308 |
+
|
| 309 |
+
# converts coo sparse matrix into full matrix
|
| 310 |
+
for Rijkab in H_block_sparse.keys():
|
| 311 |
+
sparse_form = H_block_sparse[Rijkab]
|
| 312 |
+
ia1 = int(Rijkab[1:-1].split(',')[3])
|
| 313 |
+
ia2 = int(Rijkab[1:-1].split(',')[4])
|
| 314 |
+
tmpt = np.zeros((int(atom2nu[ia1-1]),int(atom2nu[ia2-1])))
|
| 315 |
+
for i in range(len(sparse_form)):
|
| 316 |
+
tmpt[int(sparse_form[i][0]),int(sparse_form[i][1])]=sparse_form[i][2]/0.036749324533634074/2
|
| 317 |
+
H_block_sparse[Rijkab]=tmpt
|
| 318 |
+
f.close()
|
| 319 |
+
f = h5py.File('{}/hamiltonians.h5'.format(output_path),'w')
|
| 320 |
+
for Rijkab in H_block_sparse.keys():
|
| 321 |
+
f[Rijkab] = H_block_sparse[Rijkab]
|
| 322 |
+
|
| 323 |
+
for Rijkab in S_block_sparse.keys():
|
| 324 |
+
sparse_form = S_block_sparse[Rijkab]
|
| 325 |
+
ia1 = int(Rijkab[1:-1].split(',')[3])
|
| 326 |
+
ia2 = int(Rijkab[1:-1].split(',')[4])
|
| 327 |
+
tmpt = np.zeros((int(atom2nu[ia1-1]),int(atom2nu[ia2-1])))
|
| 328 |
+
for i in range(len(sparse_form)):
|
| 329 |
+
tmpt[int(sparse_form[i][0]),int(sparse_form[i][1])]=sparse_form[i][2]
|
| 330 |
+
S_block_sparse[Rijkab]=tmpt
|
| 331 |
+
|
| 332 |
+
f.close()
|
| 333 |
+
f = h5py.File('{}/overlaps.h5'.format(output_path),'w')
|
| 334 |
+
for Rijkab in S_block_sparse.keys():
|
| 335 |
+
f[Rijkab] = S_block_sparse[Rijkab]
|
| 336 |
+
f.close()
|
2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/scripts/__init__.py
ADDED
|
File without changes
|
2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/scripts/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (154 Bytes). View file
|
|
|
2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/scripts/__pycache__/preprocess.cpython-312.pyc
ADDED
|
Binary file (14.5 kB). View file
|
|
|
2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/scripts/__pycache__/train.cpython-312.pyc
ADDED
|
Binary file (1.36 kB). View file
|
|
|
2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/scripts/inference.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import time
|
| 3 |
+
import subprocess as sp
|
| 4 |
+
import json
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
|
| 8 |
+
from deeph import get_inference_config, rotate_back, abacus_parse
|
| 9 |
+
from deeph.preprocess import openmx_parse_overlap, get_rc
|
| 10 |
+
from deeph.inference import predict, predict_with_grad
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def main():
|
| 14 |
+
parser = argparse.ArgumentParser(description='Deep Hamiltonian')
|
| 15 |
+
parser.add_argument('--config', default=[], nargs='+', type=str, metavar='N')
|
| 16 |
+
args = parser.parse_args()
|
| 17 |
+
|
| 18 |
+
print(f'User config name: {args.config}')
|
| 19 |
+
config = get_inference_config(args.config)
|
| 20 |
+
|
| 21 |
+
work_dir = os.path.abspath(config.get('basic', 'work_dir'))
|
| 22 |
+
OLP_dir = os.path.abspath(config.get('basic', 'OLP_dir'))
|
| 23 |
+
interface = config.get('basic', 'interface')
|
| 24 |
+
abacus_suffix = str(config.get('basic', 'abacus_suffix', fallback='ABACUS'))
|
| 25 |
+
task = json.loads(config.get('basic', 'task'))
|
| 26 |
+
assert isinstance(task, list)
|
| 27 |
+
eigen_solver = config.get('basic', 'eigen_solver')
|
| 28 |
+
disable_cuda = config.getboolean('basic', 'disable_cuda')
|
| 29 |
+
device = config.get('basic', 'device')
|
| 30 |
+
huge_structure = config.getboolean('basic', 'huge_structure')
|
| 31 |
+
restore_blocks_py = config.getboolean('basic', 'restore_blocks_py')
|
| 32 |
+
gen_rc_idx = config.getboolean('basic', 'gen_rc_idx')
|
| 33 |
+
gen_rc_by_idx = config.get('basic', 'gen_rc_by_idx')
|
| 34 |
+
with_grad = config.getboolean('basic', 'with_grad')
|
| 35 |
+
julia_interpreter = config.get('interpreter', 'julia_interpreter', fallback='')
|
| 36 |
+
python_interpreter = config.get('interpreter', 'python_interpreter', fallback='')
|
| 37 |
+
radius = config.getfloat('graph', 'radius')
|
| 38 |
+
|
| 39 |
+
if 5 in task:
|
| 40 |
+
if eigen_solver in ['sparse_jl', 'dense_jl']:
|
| 41 |
+
assert julia_interpreter, "Please specify julia_interpreter to use Julia code to calculate eigenpairs"
|
| 42 |
+
elif eigen_solver in ['dense_py']:
|
| 43 |
+
assert python_interpreter, "Please specify python_interpreter to use Python code to calculate eigenpairs"
|
| 44 |
+
else:
|
| 45 |
+
raise ValueError(f"Unknown eigen_solver: {eigen_solver}")
|
| 46 |
+
if 3 in task and not restore_blocks_py:
|
| 47 |
+
assert julia_interpreter, "Please specify julia_interpreter to use Julia code to rearrange matrix blocks"
|
| 48 |
+
|
| 49 |
+
if with_grad:
|
| 50 |
+
assert restore_blocks_py is True
|
| 51 |
+
assert 4 not in task
|
| 52 |
+
assert 5 not in task
|
| 53 |
+
|
| 54 |
+
os.makedirs(work_dir, exist_ok=True)
|
| 55 |
+
config.write(open(os.path.join(work_dir, 'config.ini'), "w"))
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
if not restore_blocks_py:
|
| 59 |
+
cmd3_post = f"{julia_interpreter} " \
|
| 60 |
+
f"{os.path.join(os.path.dirname(os.path.dirname(__file__)), 'inference', 'restore_blocks.jl')} " \
|
| 61 |
+
f"--input_dir {work_dir} --output_dir {work_dir}"
|
| 62 |
+
|
| 63 |
+
if eigen_solver == 'sparse_jl':
|
| 64 |
+
cmd5 = f"{julia_interpreter} " \
|
| 65 |
+
f"{os.path.join(os.path.dirname(os.path.dirname(__file__)), 'inference', 'sparse_calc.jl')} " \
|
| 66 |
+
f"--input_dir {work_dir} --output_dir {work_dir} --config {config.get('basic', 'sparse_calc_config')}"
|
| 67 |
+
elif eigen_solver == 'dense_jl':
|
| 68 |
+
cmd5 = f"{julia_interpreter} " \
|
| 69 |
+
f"{os.path.join(os.path.dirname(os.path.dirname(__file__)), 'inference', 'dense_calc.jl')} " \
|
| 70 |
+
f"--input_dir {work_dir} --output_dir {work_dir} --config {config.get('basic', 'sparse_calc_config')}"
|
| 71 |
+
elif eigen_solver == 'dense_py':
|
| 72 |
+
cmd5 = f"{python_interpreter} " \
|
| 73 |
+
f"{os.path.join(os.path.dirname(os.path.dirname(__file__)), 'inference', 'dense_calc.py')} " \
|
| 74 |
+
f"--input_dir {work_dir} --output_dir {work_dir} --config {config.get('basic', 'sparse_calc_config')}"
|
| 75 |
+
else:
|
| 76 |
+
raise ValueError(f"Unknown eigen_solver: {eigen_solver}")
|
| 77 |
+
|
| 78 |
+
print(f"\n~~~~~~~ 1.parse_Overlap\n")
|
| 79 |
+
print(f"\n~~~~~~~ 2.get_local_coordinate\n")
|
| 80 |
+
print(f"\n~~~~~~~ 3.get_pred_Hamiltonian\n")
|
| 81 |
+
if not restore_blocks_py:
|
| 82 |
+
print(f"\n~~~~~~~ 3_post.restore_blocks, command: \n{cmd3_post}\n")
|
| 83 |
+
print(f"\n~~~~~~~ 4.rotate_back\n")
|
| 84 |
+
print(f"\n~~~~~~~ 5.sparse_calc, command: \n{cmd5}\n")
|
| 85 |
+
|
| 86 |
+
if 1 in task:
|
| 87 |
+
begin = time.time()
|
| 88 |
+
print(f"\n####### Begin 1.parse_Overlap")
|
| 89 |
+
if interface == 'openmx':
|
| 90 |
+
assert os.path.exists(os.path.join(OLP_dir, 'openmx.out')), "Necessary files could not be found in OLP_dir"
|
| 91 |
+
assert os.path.exists(os.path.join(OLP_dir, 'output')), "Necessary files could not be found in OLP_dir"
|
| 92 |
+
openmx_parse_overlap(OLP_dir, work_dir)
|
| 93 |
+
elif interface == 'abacus':
|
| 94 |
+
print("Output subdirectories:", "OUT." + abacus_suffix)
|
| 95 |
+
assert os.path.exists(os.path.join(OLP_dir, 'SR.csr')), "Necessary files could not be found in OLP_dir"
|
| 96 |
+
assert os.path.exists(os.path.join(OLP_dir, f'OUT.{abacus_suffix}')), "Necessary files could not be found in OLP_dir"
|
| 97 |
+
abacus_parse(OLP_dir, work_dir, data_name=f'OUT.{abacus_suffix}', only_S=True)
|
| 98 |
+
assert os.path.exists(os.path.join(work_dir, "overlaps.h5"))
|
| 99 |
+
assert os.path.exists(os.path.join(work_dir, "lat.dat"))
|
| 100 |
+
assert os.path.exists(os.path.join(work_dir, "rlat.dat"))
|
| 101 |
+
assert os.path.exists(os.path.join(work_dir, "site_positions.dat"))
|
| 102 |
+
assert os.path.exists(os.path.join(work_dir, "orbital_types.dat"))
|
| 103 |
+
assert os.path.exists(os.path.join(work_dir, "element.dat"))
|
| 104 |
+
print('\n******* Finish 1.parse_Overlap, cost %d seconds\n' % (time.time() - begin))
|
| 105 |
+
|
| 106 |
+
if not with_grad and 2 in task:
|
| 107 |
+
begin = time.time()
|
| 108 |
+
print(f"\n####### Begin 2.get_local_coordinate")
|
| 109 |
+
get_rc(work_dir, work_dir, radius=radius, gen_rc_idx=gen_rc_idx, gen_rc_by_idx=gen_rc_by_idx,
|
| 110 |
+
create_from_DFT=config.getboolean('graph', 'create_from_DFT'))
|
| 111 |
+
assert os.path.exists(os.path.join(work_dir, "rc.h5"))
|
| 112 |
+
print('\n******* Finish 2.get_local_coordinate, cost %d seconds\n' % (time.time() - begin))
|
| 113 |
+
|
| 114 |
+
if 3 in task:
|
| 115 |
+
begin = time.time()
|
| 116 |
+
print(f"\n####### Begin 3.get_pred_Hamiltonian")
|
| 117 |
+
trained_model_dir = config.get('basic', 'trained_model_dir')
|
| 118 |
+
if trained_model_dir[0] == '[' and trained_model_dir[-1] == ']':
|
| 119 |
+
trained_model_dir = json.loads(trained_model_dir)
|
| 120 |
+
if with_grad:
|
| 121 |
+
predict_with_grad(input_dir=work_dir, output_dir=work_dir, disable_cuda=disable_cuda, device=device,
|
| 122 |
+
huge_structure=huge_structure, trained_model_dirs=trained_model_dir)
|
| 123 |
+
else:
|
| 124 |
+
predict(input_dir=work_dir, output_dir=work_dir, disable_cuda=disable_cuda, device=device,
|
| 125 |
+
huge_structure=huge_structure, restore_blocks_py=restore_blocks_py,
|
| 126 |
+
trained_model_dirs=trained_model_dir)
|
| 127 |
+
if restore_blocks_py:
|
| 128 |
+
if with_grad:
|
| 129 |
+
assert os.path.exists(os.path.join(work_dir, "hamiltonians_grad_pred.h5"))
|
| 130 |
+
assert os.path.exists(os.path.join(work_dir, "hamiltonians_pred.h5"))
|
| 131 |
+
else:
|
| 132 |
+
assert os.path.exists(os.path.join(work_dir, "rh_pred.h5"))
|
| 133 |
+
else:
|
| 134 |
+
capture_output = sp.run(cmd3_post, shell=True, capture_output=False, encoding="utf-8")
|
| 135 |
+
assert capture_output.returncode == 0
|
| 136 |
+
assert os.path.exists(os.path.join(work_dir, "rh_pred.h5"))
|
| 137 |
+
print('\n******* Finish 3.get_pred_Hamiltonian, cost %d seconds\n' % (time.time() - begin))
|
| 138 |
+
|
| 139 |
+
if 4 in task:
|
| 140 |
+
begin = time.time()
|
| 141 |
+
print(f"\n####### Begin 4.rotate_back")
|
| 142 |
+
rotate_back(input_dir=work_dir, output_dir=work_dir)
|
| 143 |
+
assert os.path.exists(os.path.join(work_dir, "hamiltonians_pred.h5"))
|
| 144 |
+
print('\n******* Finish 4.rotate_back, cost %d seconds\n' % (time.time() - begin))
|
| 145 |
+
|
| 146 |
+
if 5 in task:
|
| 147 |
+
begin = time.time()
|
| 148 |
+
print(f"\n####### Begin 5.sparse_calc")
|
| 149 |
+
capture_output = sp.run(cmd5, shell=True, capture_output=False, encoding="utf-8")
|
| 150 |
+
assert capture_output.returncode == 0
|
| 151 |
+
if eigen_solver in ['sparse_jl']:
|
| 152 |
+
assert os.path.exists(os.path.join(work_dir, "sparse_matrix.jld"))
|
| 153 |
+
print('\n******* Finish 5.sparse_calc, cost %d seconds\n' % (time.time() - begin))
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
if __name__ == '__main__':
|
| 157 |
+
main()
|
2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/scripts/preprocess.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import subprocess as sp
|
| 3 |
+
import time
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import argparse
|
| 7 |
+
from pathos.multiprocessing import ProcessingPool as Pool
|
| 8 |
+
|
| 9 |
+
from deeph import get_preprocess_config, get_rc, get_rh, abacus_parse, siesta_parse
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def collect_magmom_from_openmx(input_dir, output_dir, num_atom, mag_element):
|
| 13 |
+
magmom_data = np.zeros((num_atom, 4))
|
| 14 |
+
|
| 15 |
+
cmd = f'grep --text -A {num_atom + 3} "Total spin moment" {os.path.join(input_dir, "openmx.scfout")}'
|
| 16 |
+
magmom_str = os.popen(cmd).read().splitlines()
|
| 17 |
+
# print("Total local magnetic moment:", magmom_str[0].split()[4])
|
| 18 |
+
|
| 19 |
+
for index in range(num_atom):
|
| 20 |
+
line = magmom_str[3 + index].split()
|
| 21 |
+
assert line[0] == str(index + 1)
|
| 22 |
+
element_str = line[1]
|
| 23 |
+
magmom_r = line[5]
|
| 24 |
+
magmom_theta = line[6]
|
| 25 |
+
magmom_phi = line[7]
|
| 26 |
+
magmom_data[index] = int(element_str in mag_element), magmom_r, magmom_theta, magmom_phi
|
| 27 |
+
|
| 28 |
+
np.savetxt(os.path.join(output_dir, "magmom.txt"), magmom_data)
|
| 29 |
+
|
| 30 |
+
def collect_magmom_from_abacus(input_dir, output_dir, abacus_suffix, num_atom, mag_element): #to use this feature, be sure to turn out_chg and out_mul in abacus INPUT file, if not, will use mag setting in STRU file, and this may loss accuracy or incorrect
|
| 31 |
+
magmom_data = np.zeros((num_atom, 4))
|
| 32 |
+
|
| 33 |
+
# using running_scf.log file with INPUT file out_chg and out_mul == 1
|
| 34 |
+
cmd = f"grep 'Total Magnetism' {os.path.join(input_dir, 'OUT.' + abacus_suffix, 'running_scf.log')}"
|
| 35 |
+
datas = os.popen(cmd).read().strip().splitlines()
|
| 36 |
+
if datas:
|
| 37 |
+
for index, data in enumerate(datas):
|
| 38 |
+
element_str = data.split()[4]
|
| 39 |
+
x, y, z = map(float, data.split('(')[-1].split(')')[0].split(','))
|
| 40 |
+
vector = np.array([x, y, z])
|
| 41 |
+
r = np.linalg.norm(vector)
|
| 42 |
+
theta = np.degrees(np.arctan2(vector[1], vector[0]))
|
| 43 |
+
phi = np.degrees(np.arccos(vector[2] / r))
|
| 44 |
+
magmom_data[index] = int(element_str in mag_element), r, theta, phi
|
| 45 |
+
else: # using STRU file magmom setting, THIS MAY CAUSE WRONG OUTPUT!
|
| 46 |
+
index_atom = 0
|
| 47 |
+
with open(os.path.join(input_dir, "STRU"), 'r') as file:
|
| 48 |
+
lines = file.readlines()
|
| 49 |
+
for k in range(len(lines)): # k = line index
|
| 50 |
+
if lines[k].strip() == 'ATOMIC_POSITIONS':
|
| 51 |
+
kk = k + 2 # kk = current line index
|
| 52 |
+
while kk < len(lines):
|
| 53 |
+
if lines[kk] == "\n": # for if empty line between two elements, as ABACUS accepts
|
| 54 |
+
continue
|
| 55 |
+
element_str = lines[kk].strip()
|
| 56 |
+
element_amount = int(lines[kk + 2].strip())
|
| 57 |
+
for j in range(element_amount):
|
| 58 |
+
line = lines[kk + 3 + j].strip().split()
|
| 59 |
+
if len(line) < 11: # check if magmom is included
|
| 60 |
+
raise ValueError('this line do not contain magmom: {} in this file: {}'.format(line, input_dir))
|
| 61 |
+
if line[7] != "angle1" and line[8] != "angle1": # check if magmom is in angle mode
|
| 62 |
+
raise ValueError('mag in STRU should be mag * angle1 * angle2 *')
|
| 63 |
+
if line[6] == "mag": # for if 'm' is included
|
| 64 |
+
index_str = 7
|
| 65 |
+
else:
|
| 66 |
+
index_str = 8
|
| 67 |
+
magmom_data[index_atom] = int(element_str in mag_element), line[index_str], line[index_str + 2], line[index_str + 4]
|
| 68 |
+
index_atom += 1
|
| 69 |
+
kk += 3 + element_amount
|
| 70 |
+
|
| 71 |
+
np.savetxt(os.path.join(output_dir, "magmom.txt"), magmom_data)
|
| 72 |
+
|
| 73 |
+
def main():
|
| 74 |
+
parser = argparse.ArgumentParser(description='Deep Hamiltonian')
|
| 75 |
+
parser.add_argument('--config', default=[], nargs='+', type=str, metavar='N')
|
| 76 |
+
args = parser.parse_args()
|
| 77 |
+
|
| 78 |
+
print(f'User config name: {args.config}')
|
| 79 |
+
config = get_preprocess_config(args.config)
|
| 80 |
+
|
| 81 |
+
raw_dir = os.path.abspath(config.get('basic', 'raw_dir'))
|
| 82 |
+
processed_dir = os.path.abspath(config.get('basic', 'processed_dir'))
|
| 83 |
+
abacus_suffix = str(config.get('basic', 'abacus_suffix', fallback='ABACUS'))
|
| 84 |
+
target = config.get('basic', 'target')
|
| 85 |
+
interface = config.get('basic', 'interface')
|
| 86 |
+
local_coordinate = config.getboolean('basic', 'local_coordinate')
|
| 87 |
+
multiprocessing = config.getint('basic', 'multiprocessing')
|
| 88 |
+
get_S = config.getboolean('basic', 'get_S')
|
| 89 |
+
|
| 90 |
+
julia_interpreter = config.get('interpreter', 'julia_interpreter')
|
| 91 |
+
|
| 92 |
+
def make_cmd(input_dir, output_dir, target, interface, get_S):
|
| 93 |
+
if interface == 'openmx':
|
| 94 |
+
if target == 'hamiltonian':
|
| 95 |
+
cmd = f"{julia_interpreter} " \
|
| 96 |
+
f"{os.path.join(os.path.dirname(os.path.dirname(__file__)), 'preprocess', 'openmx_get_data.jl')} " \
|
| 97 |
+
f"--input_dir {input_dir} --output_dir {output_dir} --save_overlap {str(get_S).lower()}"
|
| 98 |
+
elif target == 'density_matrix':
|
| 99 |
+
cmd = f"{julia_interpreter} " \
|
| 100 |
+
f"{os.path.join(os.path.dirname(os.path.dirname(__file__)), 'preprocess', 'openmx_get_data.jl')} " \
|
| 101 |
+
f"--input_dir {input_dir} --output_dir {output_dir} --save_overlap {str(get_S).lower()} --if_DM true"
|
| 102 |
+
else:
|
| 103 |
+
raise ValueError('Unknown target: {}'.format(target))
|
| 104 |
+
elif interface == 'siesta' or interface == 'abacus':
|
| 105 |
+
cmd = ''
|
| 106 |
+
elif interface == 'aims':
|
| 107 |
+
cmd = f"{julia_interpreter} " \
|
| 108 |
+
f"{os.path.join(os.path.dirname(os.path.dirname(__file__)), 'preprocess', 'aims_get_data.jl')} " \
|
| 109 |
+
f"--input_dir {input_dir} --output_dir {output_dir} --save_overlap {str(get_S).lower()}"
|
| 110 |
+
else:
|
| 111 |
+
raise ValueError('Unknown interface: {}'.format(interface))
|
| 112 |
+
return cmd
|
| 113 |
+
|
| 114 |
+
os.chdir(raw_dir)
|
| 115 |
+
relpath_list = []
|
| 116 |
+
abspath_list = []
|
| 117 |
+
for root, dirs, files in os.walk('./'):
|
| 118 |
+
if (interface == 'openmx' and 'openmx.scfout' in files) or (
|
| 119 |
+
interface == 'abacus' and 'OUT.' + abacus_suffix in dirs) or (
|
| 120 |
+
interface == 'siesta' and any(['.HSX' in ifile for ifile in files])) or (
|
| 121 |
+
interface == 'aims' and 'NoTB.dat' in files):
|
| 122 |
+
relpath_list.append(root)
|
| 123 |
+
abspath_list.append(os.path.abspath(root))
|
| 124 |
+
|
| 125 |
+
os.makedirs(processed_dir, exist_ok=True)
|
| 126 |
+
os.chdir(processed_dir)
|
| 127 |
+
print(f"Found {len(abspath_list)} directories to preprocess")
|
| 128 |
+
|
| 129 |
+
def worker(index):
|
| 130 |
+
time_cost = time.time() - begin_time
|
| 131 |
+
current_block = index // nodes
|
| 132 |
+
if current_block < 1:
|
| 133 |
+
time_estimate = '?'
|
| 134 |
+
else:
|
| 135 |
+
num_blocks = (len(abspath_list) + nodes - 1) // nodes
|
| 136 |
+
time_estimate = time.localtime(time_cost / (current_block) * (num_blocks - current_block))
|
| 137 |
+
time_estimate = time.strftime("%H:%M:%S", time_estimate)
|
| 138 |
+
print(f'\rPreprocessing No. {index + 1}/{len(abspath_list)} '
|
| 139 |
+
f'[{time.strftime("%H:%M:%S", time.localtime(time_cost))}<{time_estimate}]...', end='')
|
| 140 |
+
abspath = abspath_list[index]
|
| 141 |
+
relpath = relpath_list[index]
|
| 142 |
+
os.makedirs(relpath, exist_ok=True)
|
| 143 |
+
cmd = make_cmd(
|
| 144 |
+
abspath,
|
| 145 |
+
os.path.abspath(relpath),
|
| 146 |
+
target=target,
|
| 147 |
+
interface=interface,
|
| 148 |
+
get_S=get_S,
|
| 149 |
+
)
|
| 150 |
+
capture_output = sp.run(cmd, shell=True, capture_output=True, encoding="utf-8")
|
| 151 |
+
if capture_output.returncode != 0:
|
| 152 |
+
with open(os.path.join(os.path.abspath(relpath), 'error.log'), 'w') as f:
|
| 153 |
+
f.write(f'[stdout of cmd "{cmd}"]:\n\n{capture_output.stdout}\n\n\n'
|
| 154 |
+
f'[stderr of cmd "{cmd}"]:\n\n{capture_output.stderr}')
|
| 155 |
+
print(f'\nFailed to preprocess: {abspath}, '
|
| 156 |
+
f'log file was saved to {os.path.join(os.path.abspath(relpath), "error.log")}')
|
| 157 |
+
return
|
| 158 |
+
|
| 159 |
+
if interface == 'abacus':
|
| 160 |
+
print("Output subdirectories:", "OUT." + abacus_suffix)
|
| 161 |
+
abacus_parse(abspath, os.path.abspath(relpath), 'OUT.' + abacus_suffix)
|
| 162 |
+
elif interface == 'siesta':
|
| 163 |
+
siesta_parse(abspath, os.path.abspath(relpath))
|
| 164 |
+
if local_coordinate:
|
| 165 |
+
get_rc(os.path.abspath(relpath), os.path.abspath(relpath), radius=config.getfloat('graph', 'radius'),
|
| 166 |
+
r2_rand=config.getboolean('graph', 'r2_rand'),
|
| 167 |
+
create_from_DFT=config.getboolean('graph', 'create_from_DFT'), neighbour_file='hamiltonians.h5')
|
| 168 |
+
get_rh(os.path.abspath(relpath), os.path.abspath(relpath), target)
|
| 169 |
+
if config.getboolean('magnetic_moment', 'parse_magnetic_moment'):
|
| 170 |
+
num_atom = np.loadtxt(os.path.join(os.path.abspath(relpath), 'element.dat')).shape[0]
|
| 171 |
+
if interface == 'openmx':
|
| 172 |
+
collect_magmom_from_openmx(
|
| 173 |
+
abspath, os.path.abspath(relpath),
|
| 174 |
+
num_atom, eval(config.get('magnetic_moment', 'magnetic_element')))
|
| 175 |
+
elif interface == 'abacus':
|
| 176 |
+
collect_magmom_from_abacus(
|
| 177 |
+
abspath, os.path.abspath(relpath), abacus_suffix,
|
| 178 |
+
num_atom, eval(config.get('magnetic_moment', 'magnetic_element')))
|
| 179 |
+
else:
|
| 180 |
+
raise ValueError('Magnetic moment can only be parsed from OpenMX or ABACUS output for now, but your interface is {}'.format(interface))
|
| 181 |
+
|
| 182 |
+
begin_time = time.time()
|
| 183 |
+
if multiprocessing != 0:
|
| 184 |
+
if multiprocessing > 0:
|
| 185 |
+
pool_dict = {'nodes': multiprocessing}
|
| 186 |
+
else:
|
| 187 |
+
pool_dict = {}
|
| 188 |
+
with Pool(**pool_dict) as pool:
|
| 189 |
+
nodes = pool.nodes
|
| 190 |
+
print(f'Use multiprocessing (nodes = {nodes})')
|
| 191 |
+
pool.map(worker, range(len(abspath_list)))
|
| 192 |
+
else:
|
| 193 |
+
nodes = 1
|
| 194 |
+
for index in range(len(abspath_list)):
|
| 195 |
+
worker(index)
|
| 196 |
+
print(f'\nPreprocess finished in {time.time() - begin_time:.2f} seconds')
|
| 197 |
+
|
| 198 |
+
if __name__ == '__main__':
|
| 199 |
+
main()
|
2_training/hamiltonian/infer_sc/dataset/00/pred_ham_std/src/deeph/scripts/train.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
|
| 3 |
+
from deeph import DeepHKernel, get_config
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def main():
|
| 7 |
+
parser = argparse.ArgumentParser(description='Deep Hamiltonian')
|
| 8 |
+
parser.add_argument('--config', default=[], nargs='+', type=str, metavar='N')
|
| 9 |
+
args = parser.parse_args()
|
| 10 |
+
|
| 11 |
+
print(f'User config name: {args.config}')
|
| 12 |
+
config = get_config(args.config)
|
| 13 |
+
only_get_graph = config.getboolean('basic', 'only_get_graph')
|
| 14 |
+
kernel = DeepHKernel(config)
|
| 15 |
+
train_loader, val_loader, test_loader, transform = kernel.get_dataset(only_get_graph)
|
| 16 |
+
if only_get_graph:
|
| 17 |
+
return
|
| 18 |
+
kernel.build_model()
|
| 19 |
+
kernel.set_train()
|
| 20 |
+
kernel.train(train_loader, val_loader, test_loader)
|
| 21 |
+
|
| 22 |
+
if __name__ == '__main__':
|
| 23 |
+
main()
|