def cal_phono(self, dim=[1, 1, 1], mpi=28, openmp=1, num_machines=1, num_mpiprocs_per_machine=28, max_wallclock_seconds=86400, queue_name='gold5120'): strufile = extract_largest_number_file() stru = read_stru(self.input_dict["ntype"], strufile) for elem in stru.orbitals.keys(): stru.orbitals[elem] = os.path.basename(stru.orbitals[elem]) self.input_dict['gamma_only'] = 1 kpt = Kpt('Gamma', [1, 1, 1]) command = Code( code_name=self.code_name, cmdline_params=[f"-n {mpi}", f"-env OMP_NUM_THREADS={openmp}"], stdout_name="job.log", stderr_name="job.err", withmpi="mpirun") os.mkdir('phonon_ground') os.chdir('phonon_ground') stru.write_stru() with open("setting.conf", 'w') as f: f.write( dedent(f"""\ DIM = {' '.join(list_elem2str(dim))} ATOM_NAME = {' '.join(stru.elements)} """)) os.system('phonopy setting.conf --abacus -d') disp_list = glob('STRU-*') for i in disp_list: dst = 'disp-' + i.split('-')[-1] os.mkdir(dst) shutil.move(i, dst) os.chdir(dst) disp_stru = read_stru(self.input_dict["ntype"], i) submit_command = set_scheduler( 'torque', [command], num_machines=num_machines, num_mpiprocs_per_machine=num_mpiprocs_per_machine, run_mode='p', max_wallclock_seconds=max_wallclock_seconds, queue_name=queue_name) self.ground_scf(disp_stru, kpt) os.system(submit_command) os.chdir('../') os.chdir('../')
def STRU_to_POSCAR(cls, srcfile: str_PathLike, tofile: str_PathLike, ntype: int) -> None: """Convert STRU of ABACUS to POSCAR of VASP :params srcfile: str_PathLike, source file :params tofile: str_PathLike, converted file """ def convert_pos(elements: list, positions: dict): newpos = [] for elem in elements: for pos in positions[elem]: newpos.append(' ' + ''.ljust(20).join(list_elem2str(pos))) return newpos stru = read_stru(ntype, srcfile) line = [f"From {srcfile}"] line.append(str(stru.lat0 * BOHR_TO_A)) for i in stru.cell: line.append('\t' + '\t'.join(list_elem2str(i))) line.append(' ' + ''.ljust(10).join(stru.elements)) line.append(' ' + ''.ljust(10).join(list_elem2str(stru.numbers.values()))) line.append(stru._ctype) if stru._ctype == "Direct": line.append('\n'.join( convert_pos(stru.elements, stru.scaled_positions))) if stru._ctype == "Cartesian": line.append('\n'.join(convert_pos(stru.elements, stru.positions))) else: ValueError(f"Type {stru._ctype} is not supported for VASP.") with open(tofile, 'w') as file: file.write('\n'.join(line))
def cal_excite_relax(self, knum, ocp_set, mpi=28, openmp=1, num_machines=1, num_mpiprocs_per_machine=28, max_wallclock_seconds=86400, queue_name='gold5120'): strufile = extract_largest_number_file() stru = read_stru(self.input_dict["ntype"], glob(strufile)) for elem in stru.orbitals.keys(): stru.orbitals[elem] = os.path.basename(stru.orbitals[elem]) kpt = Kpt('Gamma', knum) os.mkdir('excite') os.chdir('excite') command = Code( code_name=self.code_name, cmdline_params=[f"-n {mpi}", f"-env OMP_NUM_THREADS={openmp}"], stdout_name="job.log", stderr_name="job.err", withmpi="mpirun") submit_command = set_scheduler( 'torque', [command], num_machines=num_machines, num_mpiprocs_per_machine=num_mpiprocs_per_machine, run_mode='p', max_wallclock_seconds=max_wallclock_seconds, queue_name=queue_name) self.excite_relax(ocp_set, stru, kpt) os.system(submit_command) os.chdir('../')
def cal_ground_cell_relax(self, knum, mpi=28, openmp=1, num_machines=1, num_mpiprocs_per_machine=28, max_wallclock_seconds=86400, queue_name='gold5120'): stru = read_stru(self.input_dict["ntype"], "STRU") kpt = Kpt('Gamma', knum) os.mkdir('ground') os.chdir('ground') command = Code( code_name=self.code_name, cmdline_params=[f"-n {mpi}", f"-env OMP_NUM_THREADS={openmp}"], stdout_name="job.log", stderr_name="job.err", withmpi="mpirun") submit_command = set_scheduler( 'torque', [command], num_machines=num_machines, num_mpiprocs_per_machine=num_mpiprocs_per_machine, run_mode='p', max_wallclock_seconds=max_wallclock_seconds, queue_name=queue_name) self.ground_cell_relax(stru, kpt) os.system(submit_command) os.chdir('../')
def _parse(self, **kwargs) -> dict: """parse output of scf calculation""" res = super()._parse(**kwargs) with open(self.logfile, 'r') as file: for line in file: if re.search(r"TOTAL ATOM NUMBER = [0-9]+", line): natom = int(re.search("[0-9]+", line).group()) force = np.zeros((natom, 3)) if re.search("TOTAL-FORCE \(eV/Angstrom\)", line): for i in range(3): file.readline() for i in range(natom): element, fx, fy, fz = file.readline().split() force[i] = (float(fx), float(fy), float(fz)) res["force_mean"] = force.mean() obj = read_stru(self.input_dict["ntype"], "OUT.test/STRU_ION_D") plist = [] for elem in obj.elements: plist = np.mean(obj.positions[elem]) res["positions_mean"] = np.mean(plist) res["lattice_mean"] = np.mean(obj.cell) return res
def cal_emission(self, num_mode): stru = read_stru(self.input_dict["ntype"], 'phonon_ground/STRU') mass = [] for elem in stru.elements: mass += [atom_data[symbol_map[elem]][3]] * stru.numbers[elem] mass = np.array(mass) * 1.660539040e-27 # in unit AMU os.mkdir('photon') shutil.copyfile(extract_largest_number_file(dst='./ground/OUT*'), 'photon/STRU_GS') shutil.copyfile(extract_largest_number_file(dst='./excite/OUT*'), 'photon/STRU_ES') shutil.copy2('phonon_ground/band.yaml', 'photon/') os.chdir('photon') Convert.STRU_to_POSCAR('STRU_GS', 'CONTCAR_GS', self.input_dict["ntype"]) Convert.STRU_to_POSCAR('STRU_ES', 'CONTCAR_ES', self.input_dict["ntype"]) from pyphotonics.photoluminescence import Photoluminescence p = Photoluminescence('./', 'CONTCAR_GS', 'CONTCAR_ES', num_mode, "phonopy", mass, 1000, shift_vector=[0.0, 0.0, 0.0]) import matplotlib.pyplot as plt print("Delta_R=", p.Delta_R) print("Delta_Q=", p.Delta_Q) print("HuangRhyes=", p.HuangRhyes) plt.figure(figsize=(10, 10)) plt.plot(p.S_omega) plt.ylabel('$S(\hbar\omega)$') plt.xlabel('Phonon energy (meV)') plt.xlim(0, 200) # plt.ylim(0, 0.01) plt.savefig('S_omega', bbox_inches='tight') p.write_S('S') A, I = p.PL(2, 2, 1.95) plt.figure(figsize=(10, 10)) plt.plot(I.__abs__()) plt.ylabel('$I(\hbar\omega)$') plt.xlabel('Photon energy (eV)') plt.xlim(1200, 2000) x_values, labels = plt.xticks() labels = [float(x) / p.resolution for x in x_values] plt.xticks(x_values, labels) plt.ylim(0, 600) plt.savefig('I', bbox_inches='tight') os.chdir('../')
def STRU_to_CIF(cls, srcfile: str_PathLike, tofile: str_PathLike, ntype: int, find_symmetry: bool = False) -> None: """Convert STRU of ABACUS to CIF(Crystallographic Information Framework) :params srcfile: str_PathLike, source file :params tofile: str_PathLike, converted file """ stru = read_stru(ntype, srcfile) stru.write_cif(tofile, find_symmetry)
def cal_phono_band(self, path, labels, points=51): os.chdir('phonon_ground') stru = read_stru(self.input_dict["ntype"], 'STRU') with open("band.conf", 'w') as f: f.write( dedent(f"""\ ATOM_NAME = {' '.join(stru.elements)} BAND = {convert_path_to_string(path)} BAND_POINTS = {points} BAND_LABELS = {' '.join(labels)} BAND_CONNECTION = .TRUE. FORCE_CONSTANTS= WRITE """)) os.system("phonopy band.conf -p -s") os.chdir('../')
from abacuskit.utils.constants import BOHR_TO_A from pathlib import Path tpath = "./" # target directory ntype = 4 E = [] a = [] V = [] lat = 10.4805927277 for i in range(0, 5): spath = Path(tpath, f"{i}") obj = read_stru(ntype, Path(spath, "STRU")) obj.set_energy(Path(spath, "OUT.test/running_scf.log")) V.append(obj.volume) E.append(obj.energy) a.append(obj.lat0 * lat * BOHR_TO_A) with open("V_E_res", 'w') as f1, open("a_E_res", 'w') as f2: for i in range(0, 5): f1.write(f"{V[i]}\t{E[i]}\n") f2.write(f"{a[i]}\t{E[i]}\n") import os factor = 1 fit_script = "fit-bulk.py" os.system(f"python {fit_script} V_E_res > hse_V_fit")
from abacuskit.schedulers.data import Code from abacuskit.calculations.plugins.exx import SetDimers, OptABFs, EXX from abacuskit.utils.IO import write_input, read_kpt, read_stru ntype = 4 ecut = 100 stru = read_stru(ntype, "STRU") Nu = [6, 5, 4, 3, 2, 1] kpt = read_kpt("KPT") input_dict = { "ntype" : ntype, "ecutwfc" : ecut, "nbands" : 200, "dr2" : 1e-6, "niter" : 400, "basis_type" : "lcao", "ks_solver" : "genelpa", "smearing" : "gaussian", "sigma" : 0.0005, "mixing_type" : "pulay", "mixing_beta" : 0.4, "pseudo_dir" : "/home/jiyy/SG15_upf", "newdm" : 1, "exx_hybrid_type": "hse", "exx_opt_orb_ecut": ecut, "exx_opt_orb_tolerence": 1e-12, "exx_ccp_rmesh_times": 1.5, "exx_dm_threshold": 1e-5, "exx_cauchy_threshold": 1e-9, "exx_schwarz_threshold": 1e-5, "exx_c_threshold": 1e-5,
''' Date: 2021-05-25 23:01:57 LastEditors: jiyuyang LastEditTime: 2021-05-25 23:01:58 Mail: [email protected], [email protected] ''' from abacuskit.postprocess.symmetry import Spacegroup from abacuskit.utils.IO import read_stru from pathlib import Path ntype = 4 filename = r"C:\Users\jiyuyang\Desktop\STRU" pardir = Path(filename).parent stru = read_stru(4, r"C:\Users\jiyuyang\Desktop\STRU") obj = Spacegroup(stru) pri_stru, kpt = obj.get_kpath() pri_stru.write_stru(pardir / "STRU-pri") kpt.write_kpt(pardir / "KPT-band")
def configure(config_file: str_PathLike, version: list) -> Return_2: """Configure commands and workflow for Autotest :params config_file: configure file for Autotest :params version: list of absolute path of executable file """ workflow = [] allcommands = [] with open(config_file, 'r') as file: text = json.load(file) src = Path(config_file).parent workflowinput = text["workflow"] for index, cal in enumerate(workflowinput.keys()): if re.match(f"cal_{index}", cal): cal_elem = workflowinput[cal] name = cal_elem.pop("name", None) if not name: raise KeyError(f"Key `name` in {cal} isn't set") code = cal_elem.pop("code", None) cmdline_params = code.pop("cmdline_params", []) stdin_name = code.pop("stdin_name", None) join_files = code.pop("join_files", False) withmpi = code.pop("withmpi", "mpirun") commands = [] for j, ver in enumerate(version): commands.append( Code(code_name=ver, cmdline_params=cmdline_params, stdin_name=stdin_name, stdout_name=f"{cal}.log", stderr_name=f"{cal}.err", join_files=join_files, withmpi=withmpi)) allcommands.append(commands) input_dict = cal_elem.pop("input_params", None) # STRU stru_file = src / cal_elem.pop("stru_file", "STRU") if stru_file.exists(): stru = read_stru(input_dict["ntype"], stru_file) for elem in stru.elements: if input_dict and "pseudo_dir" not in input_dict.keys(): stru.pps[elem] = Path(src, stru.pps[elem]) stru.orbitals[elem] = Path(src, stru.orbitals[elem]) else: stru = None # KPT kpt_file = src / cal_elem.pop("kpt_file", "KPT") if kpt_file.exists(): kpt = read_kpt(kpt_file) else: kpt = None obj = set_cal(name=name, input_dict=input_dict, stru=stru, kpt=kpt, **cal_elem) workflow.append(obj) else: raise KeyError( "Wrong keyword `cal` settings, it should be set in numerical order." ) return allcommands, workflow
from abacuskit.utils.IO import read_stru from pathlib import Path import shutil import os ppath = "/home/jiyy/ABACUS/AutoTest/new/testlib/MgO" # source file directory stru_path = Path(ppath, "STRU") filelist = os.listdir(ppath) filelist.remove("STRU") tpath = "./" # target directory ntype = 2 obj = read_stru(ntype, stru_path) latc = obj.lat0 delta = 0.01 for i in range(-1, 4): obj.lat0 = latc + i * delta spath = Path(tpath, str(i + 1)) spath.mkdir() obj.write_stru(Path(spath, "STRU")) for j in filelist: file = Path(ppath, j) shutil.copy(file, spath)