From 8bf5778a93270a4ce4373b94c953c1f8f573d7ec Mon Sep 17 00:00:00 2001 From: Jinzhe Zeng Date: Tue, 7 May 2024 03:01:23 -0400 Subject: [PATCH] fix pre-commit errors (#1540) Follow up #1533 ## Summary by CodeRabbit - **Refactor** - Updated string formatting across various modules to use f-strings for improved readability and consistency in error messages, log entries, and data output. - **Style** - Enhanced string interpolation methods from older formatting styles to modern f-string syntax across the application, ensuring uniformity and clearer code presentation. --- dpgen/auto_test/ABACUS.py | 16 ++-- dpgen/auto_test/EOS.py | 4 +- dpgen/auto_test/Elastic.py | 10 +- dpgen/auto_test/Gamma.py | 2 +- dpgen/auto_test/Interstitial.py | 60 ++++++------ dpgen/auto_test/Surface.py | 2 +- dpgen/auto_test/Vacancy.py | 2 +- dpgen/auto_test/common_equi.py | 16 ++-- dpgen/auto_test/common_prop.py | 4 +- dpgen/auto_test/gen_confs.py | 2 +- dpgen/auto_test/lib/abacus.py | 28 +++--- dpgen/auto_test/lib/lammps.py | 28 +++--- dpgen/auto_test/lib/lmp.py | 6 +- dpgen/auto_test/lib/mfp_eosfit.py | 22 ++--- dpgen/auto_test/lib/pwscf.py | 12 +-- dpgen/auto_test/lib/siesta.py | 8 +- dpgen/auto_test/lib/util.py | 6 +- dpgen/auto_test/lib/vasp.py | 20 ++-- dpgen/collect/collect.py | 2 +- dpgen/data/gen.py | 81 ++++++++-------- dpgen/data/reaction.py | 2 +- dpgen/data/surf.py | 12 +-- dpgen/data/tools/bcc.py | 4 +- dpgen/data/tools/cessp2force_lin.py | 24 +++-- dpgen/data/tools/create_random_disturb.py | 6 +- dpgen/data/tools/diamond.py | 2 +- dpgen/data/tools/fcc.py | 4 +- dpgen/data/tools/hcp.py | 2 +- dpgen/data/tools/sc.py | 4 +- dpgen/database/run.py | 12 +-- dpgen/database/vasp.py | 2 +- dpgen/dispatcher/Dispatcher.py | 2 +- dpgen/generator/lib/abacus_scf.py | 34 +++---- dpgen/generator/lib/calypso_check_outcar.py | 14 +-- dpgen/generator/lib/calypso_run_model_devi.py | 2 +- dpgen/generator/lib/calypso_run_opt.py | 20 ++-- dpgen/generator/lib/lammps.py | 32 +++---- dpgen/generator/lib/make_calypso.py | 22 ++--- dpgen/generator/lib/pwscf.py | 12 +-- dpgen/generator/lib/run_calypso.py | 65 +++++++------ dpgen/generator/lib/siesta.py | 8 +- dpgen/generator/lib/vasp.py | 2 +- dpgen/generator/run.py | 92 +++++++++---------- dpgen/remote/decide_machine.py | 2 +- dpgen/simplify/simplify.py | 2 +- dpgen/tools/relabel.py | 2 +- dpgen/util.py | 2 +- tests/generator/test_make_fp.py | 2 +- 48 files changed, 350 insertions(+), 370 deletions(-) diff --git a/dpgen/auto_test/ABACUS.py b/dpgen/auto_test/ABACUS.py index ea5ec627f..bd764f0df 100644 --- a/dpgen/auto_test/ABACUS.py +++ b/dpgen/auto_test/ABACUS.py @@ -26,7 +26,7 @@ def __init__(self, inter_parameter, path_to_poscar): def make_potential_files(self, output_dir): stru = os.path.abspath(os.path.join(output_dir, "STRU")) if not os.path.isfile(stru): - raise FileNotFoundError("No file %s" % stru) + raise FileNotFoundError(f"No file {stru}") stru_data = abacus_scf.get_abacus_STRU(stru) atom_names = stru_data["atom_names"] orb_files = stru_data["orb_files"] @@ -58,7 +58,7 @@ def make_potential_files(self, output_dir): ) if atomname not in self.potcars: raise RuntimeError( - "please specify the pseudopotential file of '%s'" % atomname + f"please specify the pseudopotential file of '{atomname}'" ) pp_orb_file.append([pp_files[iatom], self.potcars[atomname]]) @@ -70,7 +70,7 @@ def make_potential_files(self, output_dir): ) if atomname not in self.orbfile: raise RuntimeError( - "please specify the orbital file of '%s'" % atomname + f"please specify the orbital file of '{atomname}'" ) pp_orb_file.append([orb_files[iatom], self.orbfile[atomname]]) elif self.orbfile: @@ -105,7 +105,7 @@ def make_potential_files(self, output_dir): src_file = os.path.join(pp_dir, file_param) if not os.path.isfile(src_file): - raise RuntimeError("Can not find file %s" % src_file) + raise RuntimeError(f"Can not find file {src_file}") tar_file = os.path.join("pp_orb", filename_in_stru) if os.path.isfile(tar_file): os.remove(tar_file) @@ -138,8 +138,7 @@ def make_input_file(self, output_dir, task_type, task_param): incar_prop = os.path.abspath(cal_setting["input_prop"]) incar = abacus_scf.get_abacus_input_parameters(incar_prop) dlog.info( - "Detected 'input_prop' in 'relaxation', use %s as INPUT, and ignore 'cal_setting'" - % incar_prop + f"Detected 'input_prop' in 'relaxation', use {incar_prop} as INPUT, and ignore 'cal_setting'" ) # revise INCAR based on the INCAR provided in the "interaction" @@ -195,9 +194,8 @@ def make_input_file(self, output_dir, task_type, task_param): dlog.info("'basis_type' is not defined, set to be 'pw'!") self.modify_input(incar, "basis_type", "pw") if "lcao" in incar["basis_type"].lower() and not self.if_define_orb_file: - mess = ( - "The basis_type is %s, but not define orbital file!!!" - % incar["basis_type"] + mess = "The basis_type is {}, but not define orbital file!!!".format( + incar["basis_type"] ) raise RuntimeError(mess) if "deepks_model" in incar: diff --git a/dpgen/auto_test/EOS.py b/dpgen/auto_test/EOS.py index 2ab57dfcf..3593b2f72 100644 --- a/dpgen/auto_test/EOS.py +++ b/dpgen/auto_test/EOS.py @@ -81,7 +81,7 @@ def __init__(self, parameter, inter_param=None): def make_confs(self, path_to_work, path_to_equi, refine=False): path_to_work = os.path.abspath(path_to_work) if os.path.exists(path_to_work): - dlog.warning("%s already exists" % path_to_work) + dlog.warning(f"{path_to_work} already exists") else: os.makedirs(path_to_work) path_to_equi = os.path.abspath(path_to_equi) @@ -177,7 +177,7 @@ def make_confs(self, path_to_work, path_to_equi, refine=False): if not os.path.isfile(equi_contcar): raise RuntimeError( - "Can not find %s, please do relaxation first" % equi_contcar + f"Can not find {equi_contcar}, please do relaxation first" ) if self.inter_param["type"] == "abacus": diff --git a/dpgen/auto_test/Elastic.py b/dpgen/auto_test/Elastic.py index 298d0983c..5c35e5ecf 100644 --- a/dpgen/auto_test/Elastic.py +++ b/dpgen/auto_test/Elastic.py @@ -55,7 +55,7 @@ def __init__(self, parameter, inter_param=None): def make_confs(self, path_to_work, path_to_equi, refine=False): path_to_work = os.path.abspath(path_to_work) if os.path.exists(path_to_work): - dlog.warning("%s already exists" % path_to_work) + dlog.warning(f"{path_to_work} already exists") else: os.makedirs(path_to_work) path_to_equi = os.path.abspath(path_to_equi) @@ -288,10 +288,10 @@ def _compute_lower(self, output_file, all_tasks, all_res): res_data["GV"] = GV res_data["EV"] = EV res_data["uV"] = uV - ptr_data += "# Bulk Modulus BV = %.2f GPa\n" % BV - ptr_data += "# Shear Modulus GV = %.2f GPa\n" % GV - ptr_data += "# Youngs Modulus EV = %.2f GPa\n" % EV - ptr_data += "# Poission Ratio uV = %.2f\n " % uV + ptr_data += f"# Bulk Modulus BV = {BV:.2f} GPa\n" + ptr_data += f"# Shear Modulus GV = {GV:.2f} GPa\n" + ptr_data += f"# Youngs Modulus EV = {EV:.2f} GPa\n" + ptr_data += f"# Poission Ratio uV = {uV:.2f}\n " dumpfn(res_data, output_file, indent=4) diff --git a/dpgen/auto_test/Gamma.py b/dpgen/auto_test/Gamma.py index cb66ea52d..2499717eb 100644 --- a/dpgen/auto_test/Gamma.py +++ b/dpgen/auto_test/Gamma.py @@ -96,7 +96,7 @@ def __init__(self, parameter, inter_param=None): def make_confs(self, path_to_work, path_to_equi, refine=False): path_to_work = os.path.abspath(path_to_work) if os.path.exists(path_to_work): - dlog.warning("%s already exists" % path_to_work) + dlog.warning(f"{path_to_work} already exists") else: os.makedirs(path_to_work) path_to_equi = os.path.abspath(path_to_equi) diff --git a/dpgen/auto_test/Interstitial.py b/dpgen/auto_test/Interstitial.py index ae5befc5d..b0bcd46e3 100644 --- a/dpgen/auto_test/Interstitial.py +++ b/dpgen/auto_test/Interstitial.py @@ -269,9 +269,9 @@ def make_confs(self, path_to_work, path_to_equi, refine=False): print(self.insert_ele[0], file=fout) dumpfn(self.supercell, "supercell.json") pos_line[chl] = ( - "%.6f" % float(latt_param / 4 / super_latt_param) + f"{float(latt_param / 4 / super_latt_param):.6f}" + " " - + "%.6f" % float(latt_param / 2 / super_latt_param) + + f"{float(latt_param / 2 / super_latt_param):.6f}" + " 0.000000 " + self.insert_ele[0] ) @@ -291,9 +291,9 @@ def make_confs(self, path_to_work, path_to_equi, refine=False): print(self.insert_ele[0], file=fout) dumpfn(self.supercell, "supercell.json") pos_line[chl] = ( - "%.6f" % float(latt_param / 2 / super_latt_param) + f"{float(latt_param / 2 / super_latt_param):.6f}" + " " - + "%.6f" % float(latt_param / 2 / super_latt_param) + + f"{float(latt_param / 2 / super_latt_param):.6f}" + " 0.000000 " + self.insert_ele[0] ) @@ -313,11 +313,11 @@ def make_confs(self, path_to_work, path_to_equi, refine=False): print(self.insert_ele[0], file=fout) dumpfn(self.supercell, "supercell.json") pos_line[chl] = ( - "%.6f" % float(latt_param / 4 / super_latt_param) + f"{float(latt_param / 4 / super_latt_param):.6f}" + " " - + "%.6f" % float(latt_param / 4 / super_latt_param) + + f"{float(latt_param / 4 / super_latt_param):.6f}" + " " - + "%.6f" % float(latt_param / 4 / super_latt_param) + + f"{float(latt_param / 4 / super_latt_param):.6f}" + " " + self.insert_ele[0] ) @@ -354,20 +354,20 @@ def make_confs(self, path_to_work, path_to_equi, refine=False): print(self.insert_ele[0], file=fout) dumpfn(self.supercell, "supercell.json") pos_line[chl] = ( - "%.6f" % float(latt_param / 3 / super_latt_param) + f"{float(latt_param / 3 / super_latt_param):.6f}" + " " - + "%.6f" % float(latt_param / 3 / super_latt_param) + + f"{float(latt_param / 3 / super_latt_param):.6f}" + " " - + "%.6f" % float(latt_param / 3 / super_latt_param) + + f"{float(latt_param / 3 / super_latt_param):.6f}" + " " + self.insert_ele[0] ) pos_line[replace_label] = ( - "%.6f" % float(latt_param / 3 * 2 / super_latt_param) + f"{float(latt_param / 3 * 2 / super_latt_param):.6f}" + " " - + "%.6f" % float(latt_param / 3 * 2 / super_latt_param) + + f"{float(latt_param / 3 * 2 / super_latt_param):.6f}" + " " - + "%.6f" % float(latt_param / 3 * 2 / super_latt_param) + + f"{float(latt_param / 3 * 2 / super_latt_param):.6f}" + " " + self.insert_ele[0] ) @@ -388,24 +388,20 @@ def make_confs(self, path_to_work, path_to_equi, refine=False): print(self.insert_ele[0], file=fout) dumpfn(self.supercell, "supercell.json") pos_line[chl] = ( - "%.6f" - % float((latt_param + 2.1 / 2**0.5) / 2 / super_latt_param) + f"{float((latt_param + 2.1 / 2**0.5) / 2 / super_latt_param):.6f}" + " " - + "%.6f" - % float((latt_param - 2.1 / 2**0.5) / 2 / super_latt_param) + + f"{float((latt_param - 2.1 / 2**0.5) / 2 / super_latt_param):.6f}" + " " - + "%.6f" % float(latt_param / 2 / super_latt_param) + + f"{float(latt_param / 2 / super_latt_param):.6f}" + " " + self.insert_ele[0] ) pos_line[replace_label] = ( - "%.6f" - % float((latt_param - 2.1 / 2**0.5) / 2 / super_latt_param) + f"{float((latt_param - 2.1 / 2**0.5) / 2 / super_latt_param):.6f}" + " " - + "%.6f" - % float((latt_param + 2.1 / 2**0.5) / 2 / super_latt_param) + + f"{float((latt_param + 2.1 / 2**0.5) / 2 / super_latt_param):.6f}" + " " - + "%.6f" % float(latt_param / 2 / super_latt_param) + + f"{float(latt_param / 2 / super_latt_param):.6f}" + " " + self.insert_ele[0] ) @@ -426,20 +422,20 @@ def make_confs(self, path_to_work, path_to_equi, refine=False): print(self.insert_ele[0], file=fout) dumpfn(self.supercell, "supercell.json") pos_line[chl] = ( - "%.6f" % float(latt_param / 2 / super_latt_param) + f"{float(latt_param / 2 / super_latt_param):.6f}" + " " - + "%.6f" % float(latt_param / 2 / super_latt_param) + + f"{float(latt_param / 2 / super_latt_param):.6f}" + " " - + "%.6f" % float((latt_param - 2.1) / 2 / super_latt_param) + + f"{float((latt_param - 2.1) / 2 / super_latt_param):.6f}" + " " + self.insert_ele[0] ) pos_line[replace_label] = ( - "%.6f" % float(latt_param / 2 / super_latt_param) + f"{float(latt_param / 2 / super_latt_param):.6f}" + " " - + "%.6f" % float(latt_param / 2 / super_latt_param) + + f"{float(latt_param / 2 / super_latt_param):.6f}" + " " - + "%.6f" % float((latt_param + 2.1) / 2 / super_latt_param) + + f"{float((latt_param + 2.1) / 2 / super_latt_param):.6f}" + " " + self.insert_ele[0] ) @@ -483,9 +479,9 @@ def post_process(self, task_list): conf_line[-2] = ( "%6.d" % int(insert_line.split()[0]) + "%7.d" % type_num - + "%16.10f" % float(insert_line.split()[2]) - + "%16.10f" % float(insert_line.split()[3]) - + "%16.10f" % float(insert_line.split()[4]) + + f"{float(insert_line.split()[2]):16.10f}" + + f"{float(insert_line.split()[3]):16.10f}" + + f"{float(insert_line.split()[4]):16.10f}" ) with open(conf, "w+") as fout: for jj in conf_line: diff --git a/dpgen/auto_test/Surface.py b/dpgen/auto_test/Surface.py index b04123cfb..9e46d8d12 100644 --- a/dpgen/auto_test/Surface.py +++ b/dpgen/auto_test/Surface.py @@ -87,7 +87,7 @@ def __init__(self, parameter, inter_param=None): def make_confs(self, path_to_work, path_to_equi, refine=False): path_to_work = os.path.abspath(path_to_work) if os.path.exists(path_to_work): - dlog.warning("%s already exists" % path_to_work) + dlog.warning(f"{path_to_work} already exists") else: os.makedirs(path_to_work) path_to_equi = os.path.abspath(path_to_equi) diff --git a/dpgen/auto_test/Vacancy.py b/dpgen/auto_test/Vacancy.py index b298407d7..930fb2d60 100644 --- a/dpgen/auto_test/Vacancy.py +++ b/dpgen/auto_test/Vacancy.py @@ -79,7 +79,7 @@ def __init__(self, parameter, inter_param=None): def make_confs(self, path_to_work, path_to_equi, refine=False): path_to_work = os.path.abspath(path_to_work) if os.path.exists(path_to_work): - dlog.warning("%s already exists" % path_to_work) + dlog.warning(f"{path_to_work} already exists") else: os.makedirs(path_to_work) path_to_equi = os.path.abspath(path_to_equi) diff --git a/dpgen/auto_test/common_equi.py b/dpgen/auto_test/common_equi.py index bd37fb9e8..98fa208df 100644 --- a/dpgen/auto_test/common_equi.py +++ b/dpgen/auto_test/common_equi.py @@ -27,7 +27,7 @@ def make_equi(confs, inter_param, relax_param): else: ele_list = [key for key in inter_param["potcars"].keys()] # ele_list = inter_param['type_map'] - dlog.debug("ele_list %s" % ":".join(ele_list)) + dlog.debug("ele_list {}".format(":".join(ele_list))) conf_dirs = [] for conf in confs: conf_dirs.extend(glob.glob(conf)) @@ -45,8 +45,8 @@ def make_equi(confs, inter_param, relax_param): for ii in conf_dirs: os.chdir(ii) crys_type = ii.split("/")[-1] - dlog.debug("crys_type: %s" % crys_type) - dlog.debug("pwd: %s" % os.getcwd()) + dlog.debug(f"crys_type: {crys_type}") + dlog.debug(f"pwd: {os.getcwd()}") if crys_type == "std-fcc": if not os.path.exists("POSCAR"): crys.fcc1(ele_list[element_label]).to("POSCAR", "POSCAR") @@ -77,7 +77,7 @@ def make_equi(confs, inter_param, relax_param): # ... for ii in conf_dirs: crys_type = ii.split("/")[-1] - dlog.debug("crys_type: %s" % crys_type) + dlog.debug(f"crys_type: {crys_type}") if "mp-" in crys_type and not os.path.exists(os.path.join(ii, "POSCAR")): get_structure(crys_type).to("POSCAR", os.path.join(ii, "POSCAR")) @@ -130,7 +130,7 @@ def make_equi(confs, inter_param, relax_param): for ii in task_dirs: poscar = os.path.join(ii, "POSCAR") - dlog.debug("task_dir %s" % ii) + dlog.debug(f"task_dir {ii}") inter = make_calculator(inter_param, poscar) inter.make_potential_files(ii) inter.make_input_file(ii, "relaxation", relax_param) @@ -162,7 +162,7 @@ def run_equi(confs, inter_param, mdata): elif inter_type in lammps_task_type: mdata = convert_mdata(mdata, ["model_devi"]) else: - raise RuntimeError("unknown task %s, something wrong" % inter_type) + raise RuntimeError(f"unknown task {inter_type}, something wrong") # dispatch the tasks # POSCAR here is useless @@ -173,12 +173,12 @@ def run_equi(confs, inter_param, mdata): # backward_files += logs machine, resources, command, group_size = util.get_machine_info(mdata, inter_type) work_path = os.getcwd() - print("%s --> Runing... " % (work_path)) + print(f"{work_path} --> Runing... ") api_version = mdata.get("api_version", "1.0") if Version(api_version) < Version("1.0"): raise RuntimeError( - "API version %s has been removed. Please upgrade to 1.0." % api_version + f"API version {api_version} has been removed. Please upgrade to 1.0." ) elif Version(api_version) >= Version("1.0"): submission = make_submission( diff --git a/dpgen/auto_test/common_prop.py b/dpgen/auto_test/common_prop.py index 1cd821a4a..2af2e566b 100644 --- a/dpgen/auto_test/common_prop.py +++ b/dpgen/auto_test/common_prop.py @@ -155,7 +155,7 @@ def run_property(confs, inter_param, property_list, mdata): elif inter_type in lammps_task_type: mdata = convert_mdata(mdata, ["model_devi"]) else: - raise RuntimeError("unknown task %s, something wrong" % inter_type) + raise RuntimeError(f"unknown task {inter_type}, something wrong") work_path = path_to_work all_task = tmp_task_list @@ -199,7 +199,7 @@ def worker( api_version = mdata.get("api_version", "1.0") if Version(api_version) < Version("1.0"): raise RuntimeError( - "API version %s has been removed. Please upgrade to 1.0." % api_version + f"API version {api_version} has been removed. Please upgrade to 1.0." ) elif Version(api_version) >= Version("1.0"): submission = make_submission( diff --git a/dpgen/auto_test/gen_confs.py b/dpgen/auto_test/gen_confs.py index 2c23ed101..e74a371fe 100755 --- a/dpgen/auto_test/gen_confs.py +++ b/dpgen/auto_test/gen_confs.py @@ -134,7 +134,7 @@ def _main(): ) args = parser.parse_args() - print("generate %s" % (args.elements)) + print(f"generate {args.elements}") if len(args.elements) == 1: gen_element(args.elements[0], args.key) # gen_element_std(args.elements[0]) diff --git a/dpgen/auto_test/lib/abacus.py b/dpgen/auto_test/lib/abacus.py index 34b53af62..78345ade3 100644 --- a/dpgen/auto_test/lib/abacus.py +++ b/dpgen/auto_test/lib/abacus.py @@ -162,29 +162,29 @@ def poscar2stru(poscar, inter_param, stru="STRU"): else: atom_mass_dict = inter_param["atom_masses"] for atom in stru_data["atom_names"]: - assert atom in atom_mass_dict, ( - "the mass of %s is not defined in interaction:atom_masses" % atom - ) + assert ( + atom in atom_mass_dict + ), f"the mass of {atom} is not defined in interaction:atom_masses" atom_mass.append(atom_mass_dict[atom]) if "potcars" in inter_param: pseudo = [] for atom in stru_data["atom_names"]: - assert atom in inter_param["potcars"], ( - "the pseudopotential of %s is not defined in interaction:potcars" % atom - ) + assert ( + atom in inter_param["potcars"] + ), f"the pseudopotential of {atom} is not defined in interaction:potcars" pseudo.append("./pp_orb/" + inter_param["potcars"][atom].split("/")[-1]) if "orb_files" in inter_param: orb = [] for atom in stru_data["atom_names"]: - assert atom in inter_param["orb_files"], ( - "orbital file of %s is not defined in interaction:orb_files" % atom - ) + assert ( + atom in inter_param["orb_files"] + ), f"orbital file of {atom} is not defined in interaction:orb_files" orb.append("./pp_orb/" + inter_param["orb_files"][atom].split("/")[-1]) if "deepks_desc" in inter_param: - deepks_desc = "./pp_orb/%s\n" % inter_param["deepks_desc"] + deepks_desc = "./pp_orb/{}\n".format(inter_param["deepks_desc"]) stru_string = make_unlabeled_stru( data=stru_data, @@ -240,7 +240,7 @@ def stru_fix_atom(struf, fix_atom=[True, True, True]): f1.writelines(lines) else: raise RuntimeError( - "Error: Try to modify struc file %s, but can not find it" % struf + f"Error: Try to modify struc file {struf}, but can not find it" ) @@ -310,8 +310,8 @@ def final_stru(abacus_path): out_stru = bool(line.split()[1]) logf = os.path.join(abacus_path, f"OUT.{suffix}/running_{calculation}.log") if calculation in ["relax", "cell-relax"]: - if os.path.isfile(os.path.join(abacus_path, "OUT.%s/STRU_ION_D" % suffix)): - return "OUT.%s/STRU_ION_D" % suffix + if os.path.isfile(os.path.join(abacus_path, f"OUT.{suffix}/STRU_ION_D")): + return f"OUT.{suffix}/STRU_ION_D" else: # find the final name by STRU_ION*_D, # for abacus version < v3.2.2, there has no STRU_ION_D file but has STRU_ION0_D STRU_ION1_D ... STRU_ION10_D ... @@ -338,7 +338,7 @@ def final_stru(abacus_path): elif calculation == "scf": return "STRU" else: - print("Unrecognized calculation type in %s/INPUT" % abacus_path) + print(f"Unrecognized calculation type in {abacus_path}/INPUT") return "STRU" diff --git a/dpgen/auto_test/lib/lammps.py b/dpgen/auto_test/lib/lammps.py index 947f5df7f..2813da357 100644 --- a/dpgen/auto_test/lib/lammps.py +++ b/dpgen/auto_test/lib/lammps.py @@ -107,13 +107,13 @@ def inter_deepmd(param): if Version(deepmd_version) < Version("1"): ## DeePMD-kit version == 0.x if len(models) > 1: - ret += "%s 10 model_devi.out\n" % model_list + ret += f"{model_list} 10 model_devi.out\n" else: ret += models[0] + "\n" else: ## DeePMD-kit version >= 1 if len(models) > 1: - ret += "%s out_freq 10 out_file model_devi.out\n" % model_list + ret += f"{model_list} out_freq 10 out_file model_devi.out\n" else: ret += models[0] + "\n" ret += "pair_coeff * *\n" @@ -123,10 +123,10 @@ def inter_deepmd(param): def inter_meam(param): ret = "" line = "pair_style meam \n" - line += "pair_coeff * * %s " % param["model_name"][0] + line += "pair_coeff * * {} ".format(param["model_name"][0]) for ii in param["param_type"]: line += ii + " " - line += "%s " % param["model_name"][1] + line += "{} ".format(param["model_name"][1]) for ii in param["param_type"]: line += ii + " " line += "\n" @@ -137,7 +137,7 @@ def inter_meam(param): def inter_eam_fs(param): # 06/08 eam.fs interaction ret = "" line = "pair_style eam/fs \n" - line += "pair_coeff * * %s " % param["model_name"][0] + line += "pair_coeff * * {} ".format(param["model_name"][0]) for ii in param["param_type"]: line += ii + " " line += "\n" @@ -148,7 +148,7 @@ def inter_eam_fs(param): # 06/08 eam.fs interaction def inter_eam_alloy(param): # 06/08 eam.alloy interaction ret = "" line = "pair_style eam/alloy \n" - line += "pair_coeff * * %s " % param["model_name"] + line += "pair_coeff * * {} ".format(param["model_name"]) for ii in param["param_type"]: line += ii + " " line += "\n" @@ -179,7 +179,7 @@ def make_lammps_eval(conf, type_map, interaction, param): ret += "boundary p p p\n" ret += "atom_style atomic\n" ret += "box tilt large\n" - ret += "read_data %s\n" % conf + ret += f"read_data {conf}\n" for ii in range(len(type_map)): ret += "mass %d %.3f\n" % (ii + 1, Element(type_map_list[ii]).mass) ret += "neigh_modify every 1 delay 0 check no\n" @@ -237,7 +237,7 @@ def make_lammps_equi( ret += "boundary p p p\n" ret += "atom_style atomic\n" ret += "box tilt large\n" - ret += "read_data %s\n" % conf + ret += f"read_data {conf}\n" for ii in range(len(type_map)): ret += "mass %d %.3f\n" % (ii + 1, Element(type_map_list[ii]).mass) ret += "neigh_modify every 1 delay 0 check no\n" @@ -294,7 +294,7 @@ def make_lammps_elastic( ret += "boundary p p p\n" ret += "atom_style atomic\n" ret += "box tilt large\n" - ret += "read_data %s\n" % conf + ret += f"read_data {conf}\n" for ii in range(len(type_map)): ret += "mass %d %.3f\n" % (ii + 1, Element(type_map_list[ii]).mass) ret += "neigh_modify every 1 delay 0 check no\n" @@ -348,9 +348,9 @@ def make_lammps_press_relax( ret = "" ret += "clear\n" ret += "variable GPa2bar equal 1e4\n" - ret += "variable B0 equal %f\n" % B0 - ret += "variable bp equal %f\n" % bp - ret += "variable xx equal %f\n" % scale2equi + ret += f"variable B0 equal {B0:f}\n" + ret += f"variable bp equal {bp:f}\n" + ret += f"variable xx equal {scale2equi:f}\n" ret += "variable yeta equal 1.5*(${bp}-1)\n" ret += "variable Px0 equal 3*${B0}*(1-${xx})/${xx}^2*exp(${yeta}*(1-${xx}))\n" ret += "variable Px equal ${Px0}*${GPa2bar}\n" @@ -359,7 +359,7 @@ def make_lammps_press_relax( ret += "boundary p p p\n" ret += "atom_style atomic\n" ret += "box tilt large\n" - ret += "read_data %s\n" % conf + ret += f"read_data {conf}\n" for ii in range(len(type_map)): ret += "mass %d %.3f\n" % (ii + 1, Element(type_map_list[ii]).mass) ret += "neigh_modify every 1 delay 0 check no\n" @@ -406,7 +406,7 @@ def make_lammps_phonon( ret += "boundary p p p\n" ret += "atom_style atomic\n" ret += "box tilt large\n" - ret += "read_data %s\n" % conf + ret += f"read_data {conf}\n" ntypes = len(masses) for ii in range(ntypes): ret += "mass %d %f\n" % (ii + 1, masses[ii]) diff --git a/dpgen/auto_test/lib/lmp.py b/dpgen/auto_test/lib/lmp.py index e0894398a..11ade094e 100644 --- a/dpgen/auto_test/lib/lmp.py +++ b/dpgen/auto_test/lib/lmp.py @@ -167,9 +167,9 @@ def from_system_data(system): ntypes = len(system["atom_numbs"]) ret += "%d atoms\n" % natoms ret += "%d atom types\n" % ntypes - ret += "0 %f xlo xhi\n" % system["cell"][0][0] - ret += "0 %f ylo yhi\n" % system["cell"][1][1] - ret += "0 %f zlo zhi\n" % system["cell"][2][2] + ret += "0 {:f} xlo xhi\n".format(system["cell"][0][0]) + ret += "0 {:f} ylo yhi\n".format(system["cell"][1][1]) + ret += "0 {:f} zlo zhi\n".format(system["cell"][2][2]) ret += "{:f} {:f} {:f} xy xz yz\n".format( system["cell"][1][0], system["cell"][2][0], diff --git a/dpgen/auto_test/lib/mfp_eosfit.py b/dpgen/auto_test/lib/mfp_eosfit.py index 227012844..12adc9e65 100755 --- a/dpgen/auto_test/lib/mfp_eosfit.py +++ b/dpgen/auto_test/lib/mfp_eosfit.py @@ -1085,7 +1085,7 @@ def calc_props_SJX_5p(par): def read_ve(fin): if not os.path.exists(fin): - print("Could not find input file: [%s]" % fin) + print(f"Could not find input file: [{fin}]") os.sys.exit(-1) lines = open(fin).readlines() nline = len(lines) @@ -1107,7 +1107,7 @@ def read_ve(fin): def read_vlp(fin, fstart, fend): if not os.path.exists(fin): - print(">> Could not find input file: [%s]" % fin) + print(f">> Could not find input file: [{fin}]") os.sys.exit(-1) lines = open(fin).readlines() nline = len(lines) @@ -1192,7 +1192,7 @@ def read_vlp(fin, fstart, fend): def read_velp(fin, fstart, fend): if not os.path.exists(fin): - print(">> Could not find input file: [%s]" % fin) + print(f">> Could not find input file: [{fin}]") os.sys.exit(-1) lines = open(fin).readlines() nline = len(lines) @@ -1348,7 +1348,7 @@ def ext_vec( if show_fig: plt.show() plt.close() - print("\n>> Storing the extrapolate results in %s\n" % fout) + print(f"\n>> Storing the extrapolate results in {fout}\n") print("\n>> DONE!") return @@ -1445,7 +1445,7 @@ def ext_velp( ) fw.flush() fw.close() - print("\n>> Storing the extrapolate results in %s\n" % fout) + print(f"\n>> Storing the extrapolate results in {fout}\n") print("\n>> DONE!") return @@ -1455,7 +1455,7 @@ def lsqfit_eos( ): # make the screen output better. print("\n") - print("\t>> We are using [ %s ] to fit the V-E relationship << \t" % func) + print(f"\t>> We are using [ {func} ] to fit the V-E relationship << \t") print("\n") fs = fstart @@ -1605,7 +1605,7 @@ def lsqfit_eos( # write the fitted results in fit.out fw = open(fout, "w+") for i in range(len(popt)): - fw.write("%f\n" % popt[i]) + fw.write(f"{popt[i]:f}\n") fw.flush() fw.close() @@ -1621,14 +1621,14 @@ def lsqfit_eos( fit_res = sum(res_opt) fit_var = np.var(fvec) fit_std = np.std(fvec) - print("\nfitted residuals\t= %16e\n" % fit_res) - print("fitted variations\t= %16e\n" % fit_var) - print("standard deviations\t= %16e\n" % fit_std) + print(f"\nfitted residuals\t= {fit_res:16e}\n") + print(f"fitted variations\t= {fit_var:16e}\n") + print(f"standard deviations\t= {fit_std:16e}\n") # if fit_res > 1e-4: # print("\n>> Residuals seems too large, please refit it by swithing argument --refit 1!\n") # show = 'F' # reset show tag, not to show the figure. plt.plot(vol, en, "o", vol_i, en_i) - plt.title("EoS fitted by: %s model" % str(func)) + plt.title(f"EoS fitted by: {str(func)} model") plt.legend(["calc", func + "-fit"], loc="best") plt.xlabel("Volume (A**3)") plt.ylabel("Energy (eV)") diff --git a/dpgen/auto_test/lib/pwscf.py b/dpgen/auto_test/lib/pwscf.py index e53384003..988510f46 100644 --- a/dpgen/auto_test/lib/pwscf.py +++ b/dpgen/auto_test/lib/pwscf.py @@ -23,16 +23,16 @@ def _make_pwscf_01_runctrl(sys_data, ecut, ediff, smearing, degauss): ret += "nat = %d,\n" % tot_natoms ret += "ntyp = %d,\n" % ntypes ret += "vdw_corr = 'TS',\n" - ret += "ecutwfc = %f,\n" % ecut - ret += "ts_vdw_econv_thr=%e,\n" % ediff + ret += f"ecutwfc = {ecut:f},\n" + ret += f"ts_vdw_econv_thr={ediff:e},\n" ret += "nosym = .TRUE.,\n" if degauss is not None: - ret += "degauss = %f,\n" % degauss + ret += f"degauss = {degauss:f},\n" if smearing is not None: - ret += "smearing = '%s',\n" % (smearing.lower()) + ret += f"smearing = '{smearing.lower()}',\n" ret += "/\n" ret += "&electrons\n" - ret += "conv_thr = %e,\n" % ediff + ret += f"conv_thr = {ediff:e},\n" ret += "/\n" return ret @@ -65,7 +65,7 @@ def _make_pwscf_03_config(sys_data): ret += "CELL_PARAMETERS { angstrom }\n" for ii in range(3): for jj in range(3): - ret += "%f " % cell[ii][jj] + ret += f"{cell[ii][jj]:f} " ret += "\n" ret += "\n" ret += "ATOMIC_POSITIONS { angstrom }\n" diff --git a/dpgen/auto_test/lib/siesta.py b/dpgen/auto_test/lib/siesta.py index 9c1be6144..314dc8f2d 100644 --- a/dpgen/auto_test/lib/siesta.py +++ b/dpgen/auto_test/lib/siesta.py @@ -17,10 +17,10 @@ def _make_siesta_01_common(sys_data, ecut, ediff, mixingWeight, NumberPulay): ret += "WriteMDXmol T\n" ret += "WriteMDHistory T\n\n" - ret += "MeshCutoff %s" % str(ecut) + ret += f"MeshCutoff {str(ecut)}" ret += " Ry\n" - ret += "DM.MixingWeight %f\n" % mixingWeight - ret += "DM.Tolerance %e\n" % ediff + ret += f"DM.MixingWeight {mixingWeight:f}\n" + ret += f"DM.Tolerance {ediff:e}\n" ret += "DM.UseSaveDM true\n" ret += "DM.NumberPulay %d\n" % NumberPulay ret += "MD.UseSaveXV T\n\n" @@ -98,7 +98,7 @@ def _make_siesta_04_ucVectorCoord(sys_data): ret += "%block LatticeVectors\n" for ii in range(3): for jj in range(3): - ret += "%f " % cell[ii][jj] + ret += f"{cell[ii][jj]:f} " ret += "\n" ret += "%endblock LatticeVectors\n" diff --git a/dpgen/auto_test/lib/util.py b/dpgen/auto_test/lib/util.py index 4e355fbd1..f225e04ba 100644 --- a/dpgen/auto_test/lib/util.py +++ b/dpgen/auto_test/lib/util.py @@ -48,13 +48,13 @@ def make_work_path(jdata, task, reprod_opt, static, user): task_type = task_type + "-static-scf_incar" else: kspacing = jdata["vasp_params"]["kspacing"] - task_type = task_type + "-static-k%.2f" % (kspacing) + task_type = task_type + f"-static-k{kspacing:.2f}" else: if "relax_incar" in jdata.keys(): task_type = task_type + "-relax_incar" else: kspacing = jdata["vasp_params"]["kspacing"] - task_type = task_type + "-k%.2f" % (kspacing) + task_type = task_type + f"-k{kspacing:.2f}" elif task_type in lammps_task_type: if static: task_type = task_type + "-static" @@ -63,7 +63,7 @@ def make_work_path(jdata, task, reprod_opt, static, user): task_type = task_type + "-reprod-relax_incar" else: kspacing = jdata["vasp_params"]["kspacing"] - task_type = task_type + "-reprod-k%.2f" % (kspacing) + task_type = task_type + f"-reprod-k{kspacing:.2f}" work_path = os.path.join(task_path, task_type) assert os.path.isdir(work_path) diff --git a/dpgen/auto_test/lib/vasp.py b/dpgen/auto_test/lib/vasp.py index 1cf72f47e..a5b3623d5 100644 --- a/dpgen/auto_test/lib/vasp.py +++ b/dpgen/auto_test/lib/vasp.py @@ -273,14 +273,14 @@ def make_vasp_static_incar( ret += "ENCUT=%d\n" % ecut ret += "# ISYM=0\n" ret += "ALGO=normal\n" - ret += "EDIFF=%e\n" % ediff + ret += f"EDIFF={ediff:e}\n" ret += "EDIFFG=-0.01\n" ret += "LREAL=A\n" ret += "NPAR=%d\n" % npar ret += "KPAR=%d\n" % kpar ret += "\n" ret += "ISMEAR=%d\n" % ismear - ret += "SIGMA=%f\n" % sigma + ret += f"SIGMA={sigma:f}\n" ret += "\n" ret += "ISTART=0\n" ret += "ICHARG=2\n" @@ -295,7 +295,7 @@ def make_vasp_static_incar( ret += "PSTRESS=0\n" ret += "\n" if kspacing is not None: - ret += "KSPACING=%f\n" % kspacing + ret += f"KSPACING={kspacing:f}\n" if kgamma is not None: if kgamma: ret += "KGAMMA=T\n" @@ -323,14 +323,14 @@ def make_vasp_relax_incar( ret += "ENCUT=%d\n" % ecut ret += "# ISYM=0\n" ret += "ALGO=normal\n" - ret += "EDIFF=%e\n" % ediff + ret += f"EDIFF={ediff:e}\n" ret += "EDIFFG=-0.01\n" ret += "LREAL=A\n" ret += "NPAR=%d\n" % npar ret += "KPAR=%d\n" % kpar ret += "\n" ret += "ISMEAR=%d\n" % ismear - ret += "SIGMA=%f\n" % sigma + ret += f"SIGMA={sigma:f}\n" ret += "\n" ret += "ISTART=0\n" ret += "ICHARG=2\n" @@ -346,7 +346,7 @@ def make_vasp_relax_incar( ret += "PSTRESS=0\n" ret += "\n" if kspacing is not None: - ret += "KSPACING=%f\n" % kspacing + ret += f"KSPACING={kspacing:f}\n" if kgamma is not None: if kgamma: ret += "KGAMMA=T\n" @@ -364,14 +364,14 @@ def make_vasp_phonon_incar( ret += "ENCUT=%d\n" % ecut ret += "# ISYM=0\n" ret += "ALGO=normal\n" - ret += "EDIFF=%e\n" % ediff + ret += f"EDIFF={ediff:e}\n" ret += "EDIFFG=-0.01\n" ret += "LREAL=A\n" # ret += 'NPAR=%d\n' % npar ret += "KPAR=%d\n" % kpar ret += "\n" ret += "ISMEAR=%d\n" % ismear - ret += "SIGMA=%f\n" % sigma + ret += f"SIGMA={sigma:f}\n" ret += "\n" ret += "ISTART=0\n" ret += "ICHARG=2\n" @@ -386,7 +386,7 @@ def make_vasp_phonon_incar( ret += "PSTRESS=0\n" ret += "\n" if kspacing is not None: - ret += "KSPACING=%f\n" % kspacing + ret += f"KSPACING={kspacing:f}\n" if kgamma is not None: if kgamma: ret += "KGAMMA=T\n" @@ -455,7 +455,7 @@ def poscar_scale(poscar_in, poscar_out, scale): elif "C" == lines[7][0] or "c" == lines[7][0]: lines = _poscar_scale_cartesian(lines, scale) else: - raise RuntimeError("Unknow poscar coord style at line 7: %s" % lines[7]) + raise RuntimeError(f"Unknow poscar coord style at line 7: {lines[7]}") with open(poscar_out, "w") as fout: fout.write("".join(lines)) diff --git a/dpgen/collect/collect.py b/dpgen/collect/collect.py index ab1cc9406..133bab561 100644 --- a/dpgen/collect/collect.py +++ b/dpgen/collect/collect.py @@ -100,7 +100,7 @@ def collect_data( ii.to("deepmd/npy", os.path.join(output, out_dir)) # dump iter data for kk in coll_data.keys(): - out_dir = "sys.%s" % kk + out_dir = f"sys.{kk}" nframes = coll_data[kk].get_nframes() coll_data[kk].to("deepmd/npy", os.path.join(output, out_dir), set_size=nframes) # coll_data[kk].to('deepmd/npy', os.path.join(output, out_dir)) diff --git a/dpgen/data/gen.py b/dpgen/data/gen.py index 27134ef64..658219bde 100644 --- a/dpgen/data/gen.py +++ b/dpgen/data/gen.py @@ -114,7 +114,7 @@ def class_cell_type(jdata): elif ct == "bcc": cell_type = bcc else: - raise RuntimeError("unknown cell type %s" % ct) + raise RuntimeError(f"unknown cell type {ct}") return cell_type @@ -242,7 +242,7 @@ def poscar_scale(poscar_in, poscar_out, scale): elif "C" == lines[7][0] or "c" == lines[7][0]: lines = poscar_scale_cartesian(lines, scale) else: - raise RuntimeError("Unknow poscar style at line 7: %s" % lines[7]) + raise RuntimeError(f"Unknow poscar style at line 7: {lines[7]}") with open(poscar_out, "w") as fout: fout.write("".join(lines)) @@ -305,8 +305,8 @@ def make_super_cell(jdata): super_cell = jdata["super_cell"] path_uc = os.path.join(out_dir, global_dirname_02) path_sc = os.path.join(out_dir, global_dirname_02) - assert os.path.isdir(path_uc), "path %s should exists" % path_uc - assert os.path.isdir(path_sc), "path %s should exists" % path_sc + assert os.path.isdir(path_uc), f"path {path_uc} should exists" + assert os.path.isdir(path_sc), f"path {path_sc} should exists" # for ii in scale : from_path = path_uc @@ -325,8 +325,8 @@ def make_super_cell_ABACUS(jdata, stru_data): super_cell = jdata["super_cell"] path_uc = os.path.join(out_dir, global_dirname_02) path_sc = os.path.join(out_dir, global_dirname_02) - assert os.path.isdir(path_uc), "path %s should exists" % path_uc - assert os.path.isdir(path_sc), "path %s should exists" % path_sc + assert os.path.isdir(path_uc), f"path {path_uc} should exists" + assert os.path.isdir(path_sc), f"path {path_sc} should exists" # for ii in scale : # from_path = path_uc @@ -348,7 +348,7 @@ def make_super_cell_poscar(jdata): path_sc = os.path.join(out_dir, global_dirname_02) create_path(path_sc) from_poscar_path = jdata["from_poscar_path"] - assert os.path.isfile(from_poscar_path), "file %s should exists" % from_poscar_path + assert os.path.isfile(from_poscar_path), f"file {from_poscar_path} should exists" from_file = os.path.join(path_sc, "POSCAR.copied") shutil.copy2(from_poscar_path, from_file) @@ -388,7 +388,7 @@ def make_super_cell_STRU(jdata): path_sc = os.path.join(out_dir, global_dirname_02) create_path(path_sc) from_poscar_path = jdata["from_poscar_path"] - assert os.path.isfile(from_poscar_path), "file %s should exists" % from_poscar_path + assert os.path.isfile(from_poscar_path), f"file {from_poscar_path} should exists" from_file = os.path.join(path_sc, "STRU.copied") shutil.copy2(from_poscar_path, from_file) @@ -583,9 +583,9 @@ def make_abacus_relax(jdata, mdata): raise RuntimeError("Cannot find any k-points information.") else: relax_kpt_path = jdata["relax_kpt"] - assert os.path.isfile(relax_kpt_path), ( - "file %s should exists" % relax_kpt_path - ) + assert os.path.isfile( + relax_kpt_path + ), f"file {relax_kpt_path} should exists" else: gamma_param = {"k_points": [1, 1, 1, 0, 0, 0]} ret_kpt = make_abacus_scf_kpt(gamma_param) @@ -594,9 +594,9 @@ def make_abacus_relax(jdata, mdata): raise RuntimeError("Cannot find any k-points information.") else: relax_kpt_path = jdata["relax_kpt"] - assert os.path.isfile(relax_kpt_path), ( - "file %s should exists" % relax_kpt_path - ) + assert os.path.isfile( + relax_kpt_path + ), f"file {relax_kpt_path} should exists" out_dir = jdata["out_dir"] cwd = os.getcwd() @@ -681,7 +681,7 @@ def make_scale(jdata): "not file %s, vasp relaxation should be run before scale poscar" ) scale_path = os.path.join(work_path, ii) - scale_path = os.path.join(scale_path, "scale-%.3f" % jj) + scale_path = os.path.join(scale_path, f"scale-{jj:.3f}") create_path(scale_path) os.chdir(scale_path) poscar_scale(pos_src, "POSCAR", jj) @@ -722,7 +722,7 @@ def make_scale_ABACUS(jdata): "Can not find STRU_ION_D in OUT.ABACUS!!!\nABACUS relaxation should be run before scale poscar" ) scale_path = os.path.join(work_path, ii) - scale_path = os.path.join(scale_path, "scale-%.3f" % jj) + scale_path = os.path.join(scale_path, f"scale-{jj:.3f}") create_path(scale_path) os.chdir(scale_path) poscar_scale_abacus(pos_src, "STRU", jj, jdata) @@ -775,7 +775,7 @@ def pert_scaled(jdata): for jj in scale: path_work = path_sp path_work = os.path.join(path_work, ii) - path_work = os.path.join(path_work, "scale-%.3f" % jj) + path_work = os.path.join(path_work, f"scale-{jj:.3f}") assert os.path.isdir(path_work) os.chdir(path_work) sp.check_call(pert_cmd, shell=True) @@ -873,13 +873,13 @@ def make_vasp_md(jdata, mdata): for kk in range(pert_numb + 1): path_work = path_md path_work = os.path.join(path_work, ii) - path_work = os.path.join(path_work, "scale-%.3f" % jj) + path_work = os.path.join(path_work, f"scale-{jj:.3f}") path_work = os.path.join(path_work, "%06d" % kk) create_path(path_work) os.chdir(path_work) path_pos = path_ps path_pos = os.path.join(path_pos, ii) - path_pos = os.path.join(path_pos, "scale-%.3f" % jj) + path_pos = os.path.join(path_pos, f"scale-{jj:.3f}") path_pos = os.path.join(path_pos, "%06d" % kk) init_pos = os.path.join(path_pos, "POSCAR") shutil.copy2(init_pos, "POSCAR") @@ -927,9 +927,9 @@ def make_abacus_md(jdata, mdata): raise RuntimeError("Cannot find any k-points information.") else: md_kpt_path = jdata["md_kpt"] - assert os.path.isfile(md_kpt_path), ( - "file %s should exists" % md_kpt_path - ) + assert os.path.isfile( + md_kpt_path + ), f"file {md_kpt_path} should exists" else: ret_kpt = make_abacus_scf_kpt({"k_points": [1, 1, 1, 0, 0, 0]}) else: @@ -937,9 +937,7 @@ def make_abacus_md(jdata, mdata): raise RuntimeError("Cannot find any k-points information.") else: md_kpt_path = jdata["md_kpt"] - assert os.path.isfile(md_kpt_path), ( - "file %s should exists" % md_kpt_path - ) + assert os.path.isfile(md_kpt_path), f"file {md_kpt_path} should exists" out_dir = jdata["out_dir"] potcars = jdata["potcars"] @@ -996,13 +994,13 @@ def make_abacus_md(jdata, mdata): for kk in range(pert_numb + 1): path_work = path_md path_work = os.path.join(path_work, ii) - path_work = os.path.join(path_work, "scale-%.3f" % jj) + path_work = os.path.join(path_work, f"scale-{jj:.3f}") path_work = os.path.join(path_work, "%06d" % kk) create_path(path_work) os.chdir(path_work) path_pos = path_ps path_pos = os.path.join(path_pos, ii) - path_pos = os.path.join(path_pos, "scale-%.3f" % jj) + path_pos = os.path.join(path_pos, f"scale-{jj:.3f}") path_pos = os.path.join(path_pos, "%06d" % kk) init_pos = os.path.join(path_pos, "STRU") if "kspacing" not in standard_incar: @@ -1072,7 +1070,7 @@ def coll_vasp_md(jdata): valid_outcars = [] for jj in scale: for kk in range(pert_numb): - path_work = os.path.join("scale-%.3f" % jj, "%06d" % kk) + path_work = os.path.join(f"scale-{jj:.3f}", "%06d" % kk) outcar = os.path.join(path_work, "OUTCAR") # dlog.info("OUTCAR",outcar) if os.path.isfile(outcar): @@ -1087,8 +1085,7 @@ def coll_vasp_md(jdata): valid_outcars.append(outcar) else: dlog.info( - "WARNING : in directory %s nforce in OUTCAR is not equal to settings in INCAR" - % (os.getcwd()) + f"WARNING : in directory {os.getcwd()} nforce in OUTCAR is not equal to settings in INCAR" ) arg_cvt = " " if len(valid_outcars) == 0: @@ -1167,7 +1164,7 @@ def run_vasp_relax(jdata, mdata): api_version = mdata.get("api_version", "1.0") if Version(api_version) < Version("1.0"): raise RuntimeError( - "API version %s has been removed. Please upgrade to 1.0." % api_version + f"API version {api_version} has been removed. Please upgrade to 1.0." ) elif Version(api_version) >= Version("1.0"): @@ -1208,8 +1205,8 @@ def coll_abacus_md(jdata): valid_outcars = [] for jj in scale: for kk in range(pert_numb + 1): - path_work = os.path.join("scale-%.3f" % jj, "%06d" % kk) - print("path_work = %s" % path_work) + path_work = os.path.join(f"scale-{jj:.3f}", "%06d" % kk) + print(f"path_work = {path_work}") # outcar = os.path.join(path_work, 'OUT.ABACUS/') outcar = path_work # dlog.info("OUTCAR",outcar) @@ -1220,13 +1217,13 @@ def coll_abacus_md(jdata): print(outcar) else: dlog.info( - "WARNING : file %s does not have !FINAL_ETOT_IS note. MD simulation is not completed normally." - % os.path.join(outcar, "OUT.ABACUS/running_md.log") + "WARNING : file {} does not have !FINAL_ETOT_IS note. MD simulation is not completed normally.".format( + os.path.join(outcar, "OUT.ABACUS/running_md.log") + ) ) else: dlog.info( - "WARNING : in directory %s NO running_md.log file found." - % (os.getcwd()) + f"WARNING : in directory {os.getcwd()} NO running_md.log file found." ) arg_cvt = " " if len(valid_outcars) == 0: @@ -1307,7 +1304,7 @@ def run_abacus_relax(jdata, mdata): api_version = mdata.get("api_version", "1.0") if Version(api_version) < Version("1.0"): raise RuntimeError( - "API version %s has been removed. Please upgrade to 1.0." % api_version + f"API version {api_version} has been removed. Please upgrade to 1.0." ) elif Version(api_version) >= Version("1.0"): @@ -1368,7 +1365,7 @@ def run_vasp_md(jdata, mdata): api_version = mdata.get("api_version", "1.0") if Version(api_version) < Version("1.0"): raise RuntimeError( - "API version %s has been removed. Please upgrade to 1.0." % api_version + f"API version {api_version} has been removed. Please upgrade to 1.0." ) elif Version(api_version) >= Version("1.0"): @@ -1444,7 +1441,7 @@ def run_abacus_md(jdata, mdata): api_version = mdata.get("api_version", "1.0") if Version(api_version) < Version("1.0"): raise RuntimeError( - "API version %s has been removed. Please upgrade to 1.0." % api_version + f"API version {api_version} has been removed. Please upgrade to 1.0." ) elif Version(api_version) >= Version("1.0"): @@ -1475,7 +1472,7 @@ def gen_init_bulk(args): # Decide work path out_dir = out_dir_name(jdata) jdata["out_dir"] = out_dir - dlog.info("# working dir %s" % out_dir) + dlog.info(f"# working dir {out_dir}") # Decide whether to use a given poscar from_poscar = jdata.get("from_poscar", False) # Verify md_nstep @@ -1517,7 +1514,7 @@ def gen_init_bulk(args): for ele in jdata["elements"]: temp_elements.append(ele[0].upper() + ele[1:]) jdata["elements"] = temp_elements - dlog.info("Elements are %s" % " ".join(jdata["elements"])) + dlog.info("Elements are {}".format(" ".join(jdata["elements"]))) ## Iteration stage_list = [int(i) for i in jdata["stages"]] diff --git a/dpgen/data/reaction.py b/dpgen/data/reaction.py index f1d38bccd..b71e78c1f 100644 --- a/dpgen/data/reaction.py +++ b/dpgen/data/reaction.py @@ -204,7 +204,7 @@ def convert_data(jdata): type_map=jdata["type_map"], ) s.to_deepmd_npy(data_path) - dlog.info("Initial data is avaiable in %s" % os.path.abspath(data_path)) + dlog.info(f"Initial data is avaiable in {os.path.abspath(data_path)}") def gen_init_reaction(args): diff --git a/dpgen/data/surf.py b/dpgen/data/surf.py index 2590f9a6b..a3a60d039 100644 --- a/dpgen/data/surf.py +++ b/dpgen/data/surf.py @@ -113,7 +113,7 @@ def class_cell_type(jdata): elif ct == "bcc": cell_type = bcc else: - raise RuntimeError("unknow cell type %s" % ct) + raise RuntimeError(f"unknow cell type {ct}") return cell_type @@ -408,7 +408,7 @@ def poscar_scale(poscar_in, poscar_out, scale): elif "C" == lines[7][0] or "c" == lines[7][0]: lines = poscar_scale_cartesian(lines, scale) else: - raise RuntimeError("Unknow poscar style at line 7: %s" % lines[7]) + raise RuntimeError(f"Unknow poscar style at line 7: {lines[7]}") try: poscar = Poscar.from_string("".join(lines)) @@ -450,7 +450,7 @@ def make_scale(jdata): "not file %s, vasp relaxation should be run before scale poscar" ) scale_path = os.path.join(work_path, ii) - scale_path = os.path.join(scale_path, "scale-%.3f" % jj) + scale_path = os.path.join(scale_path, f"scale-{jj:.3f}") create_path(scale_path) os.chdir(scale_path) poscar_scale(pos_src, "POSCAR", jj) @@ -515,7 +515,7 @@ def pert_scaled(jdata): for jj in scale: path_scale = path_sp path_scale = os.path.join(path_scale, ii) - path_scale = os.path.join(path_scale, "scale-%.3f" % jj) + path_scale = os.path.join(path_scale, f"scale-{jj:.3f}") assert os.path.isdir(path_scale) os.chdir(path_scale) dlog.info(os.getcwd()) @@ -523,7 +523,7 @@ def pert_scaled(jdata): assert os.path.isfile(poscar_in) for ll in elongs: path_elong = path_scale - path_elong = os.path.join(path_elong, "elong-%3.3f" % ll) + path_elong = os.path.join(path_elong, f"elong-{ll:3.3f}") create_path(path_elong) os.chdir(path_elong) poscar_elong(poscar_in, "POSCAR", ll) @@ -611,7 +611,7 @@ def gen_init_surf(args): out_dir = out_dir_name(jdata) jdata["out_dir"] = out_dir - dlog.info("# working dir %s" % out_dir) + dlog.info(f"# working dir {out_dir}") if args.MACHINE is not None: mdata = load_file(args.MACHINE) diff --git a/dpgen/data/tools/bcc.py b/dpgen/data/tools/bcc.py index 3ba99aa6f..08554f472 100644 --- a/dpgen/data/tools/bcc.py +++ b/dpgen/data/tools/bcc.py @@ -12,8 +12,8 @@ def gen_box(): def poscar_unit(latt): box = gen_box() ret = "" - ret += "BCC : a = %f \n" % latt - ret += "%.16f\n" % (latt) + ret += f"BCC : a = {latt:f} \n" + ret += f"{latt:.16f}\n" ret += f"{box[0][0]:.16f} {box[0][1]:.16f} {box[0][2]:.16f}\n" ret += f"{box[1][0]:.16f} {box[1][1]:.16f} {box[1][2]:.16f}\n" ret += f"{box[2][0]:.16f} {box[2][1]:.16f} {box[2][2]:.16f}\n" diff --git a/dpgen/data/tools/cessp2force_lin.py b/dpgen/data/tools/cessp2force_lin.py index 2a034247b..f08f7e721 100755 --- a/dpgen/data/tools/cessp2force_lin.py +++ b/dpgen/data/tools/cessp2force_lin.py @@ -40,7 +40,7 @@ def get_outcar_files(directory, recursive): # walk directory (recursively) and return all OUTCAR* files # return list of outcars' path - sys.stderr.write("Searching directory %s for OUTCAR* files ...\n" % directory) + sys.stderr.write(f"Searching directory {directory} for OUTCAR* files ...\n") outcars = [] if not recursive: for item in os.listdir(directory): @@ -132,7 +132,7 @@ def process_outcar_file_v5_dev( windex = [nconfs - 1] # reading current OUTCAR - print("Reading %s ..." % outcars[i]) + print(f"Reading {outcars[i]} ...") count = -1 line = f.readline() while line != "": @@ -150,16 +150,16 @@ def process_outcar_file_v5_dev( if "free energy TOTEN" in line: energy = float(line.split()[4]) / natoms if count in windex: - fw.write("#N %s 1\n" % natoms) + fw.write(f"#N {natoms} 1\n") fw.write("#C ") if elements: - fw.write("%s " % numbers[0]) + fw.write(f"{numbers[0]} ") for j in range(1, max_types): - fw.write("%s\t" % numbers[j]) + fw.write(f"{numbers[j]}\t") else: - fw.write(" %s" % data[i][1][0]) + fw.write(f" {data[i][1][0]}") for j in range(1, max_types): - fw.write(" %s" % data[i][1][j]) + fw.write(f" {data[i][1][j]}") fw.write("\n") fw.write( "## force file generated from file %s config %d\n" @@ -168,12 +168,12 @@ def process_outcar_file_v5_dev( fw.write(f"#X {box_x[0]:13.8f} {box_x[1]:13.8f} {box_x[2]:13.8f}\n") fw.write(f"#Y {box_y[0]:13.8f} {box_y[1]:13.8f} {box_y[2]:13.8f}\n") fw.write(f"#Z {box_z[0]:13.8f} {box_z[1]:13.8f} {box_z[2]:13.8f}\n") - fw.write("#W %f\n" % (args.weight)) - fw.write("#E %.10f\n" % (energy)) + fw.write(f"#W {args.weight:f}\n") + fw.write(f"#E {energy:.10f}\n") if stress: fw.write("#S ") for num in range(6): - fw.write("%8.7g\t" % (stress[num])) + fw.write(f"{stress[num]:8.7g}\t") fw.write("\n") fw.write("#F\n") fw.flush() @@ -325,9 +325,7 @@ def Parser(): sys.stderr.write("\nERROR: Could not read the -c string\n") sys.exit() if number >= max_types: - sys.stderr.write( - "\nERROR: The atom type for %s is invalid!\n" % name - ) + sys.stderr.write(f"\nERROR: The atom type for {name} is invalid!\n") sys.exit() if name in types: sys.stderr.write( diff --git a/dpgen/data/tools/create_random_disturb.py b/dpgen/data/tools/create_random_disturb.py index 8814c7ff9..b3cefb07f 100755 --- a/dpgen/data/tools/create_random_disturb.py +++ b/dpgen/data/tools/create_random_disturb.py @@ -79,7 +79,7 @@ def create_disturbs_ase( pos = pos0 + dpos atoms_d.set_positions(pos) fout = fin + str(fid) + "." + ofmt - print("Creating %s ..." % fout) + print(f"Creating {fout} ...") if ofmt in ["lmp", "lammps_data"]: # for lammps, use my personal output functions io_lammps.ase2lammpsdata(atoms_d, fout) @@ -158,7 +158,7 @@ def create_disturbs_ase_dev( # Writing it fout = fin + str(fid) + "." + ofmt - print("Creating %s ..." % fout) + print(f"Creating {fout} ...") if ofmt in ["lmp", "lammps_data"]: # for lammps, use my personal output functions io_lammps.ase2lammpsdata(atoms_d, fout=fout) @@ -230,7 +230,7 @@ def create_disturbs_abacus_dev( # Writing it fout = fin + str(fid) + "." + ofmt - print("Creating %s ..." % fout) + print(f"Creating {fout} ...") ret = make_abacus_scf_stru( stru_d, stru_d["pp_files"], stru_d["orb_files"], stru_d["dpks_descriptor"] ) diff --git a/dpgen/data/tools/diamond.py b/dpgen/data/tools/diamond.py index f7d82d01e..e258a5aa6 100644 --- a/dpgen/data/tools/diamond.py +++ b/dpgen/data/tools/diamond.py @@ -18,7 +18,7 @@ def poscar_unit(latt): box = gen_box() ret = "" ret += "DIAMOND\n" - ret += "%.16f\n" % (latt) + ret += f"{latt:.16f}\n" ret += f"{box[0][0]:.16f} {box[0][1]:.16f} {box[0][2]:.16f}\n" ret += f"{box[1][0]:.16f} {box[1][1]:.16f} {box[1][2]:.16f}\n" ret += f"{box[2][0]:.16f} {box[2][1]:.16f} {box[2][2]:.16f}\n" diff --git a/dpgen/data/tools/fcc.py b/dpgen/data/tools/fcc.py index a89ef5385..3e9815851 100644 --- a/dpgen/data/tools/fcc.py +++ b/dpgen/data/tools/fcc.py @@ -12,8 +12,8 @@ def gen_box(): def poscar_unit(latt): box = gen_box() ret = "" - ret += "FCC : a = %f \n" % latt - ret += "%.16f\n" % (latt) + ret += f"FCC : a = {latt:f} \n" + ret += f"{latt:.16f}\n" ret += f"{box[0][0]:.16f} {box[0][1]:.16f} {box[0][2]:.16f}\n" ret += f"{box[1][0]:.16f} {box[1][1]:.16f} {box[1][2]:.16f}\n" ret += f"{box[2][0]:.16f} {box[2][1]:.16f} {box[2][2]:.16f}\n" diff --git a/dpgen/data/tools/hcp.py b/dpgen/data/tools/hcp.py index bfd2fa3c4..d552cdcc2 100644 --- a/dpgen/data/tools/hcp.py +++ b/dpgen/data/tools/hcp.py @@ -15,7 +15,7 @@ def gen_box(): def poscar_unit(latt): box = gen_box() ret = "" - ret += "HCP : a = %f / sqrt(2)\n" % latt + ret += f"HCP : a = {latt:f} / sqrt(2)\n" ret += "%.16f\n" % (latt / np.sqrt(2)) ret += f"{box[0][0]:.16f} {box[0][1]:.16f} {box[0][2]:.16f}\n" ret += f"{box[1][0]:.16f} {box[1][1]:.16f} {box[1][2]:.16f}\n" diff --git a/dpgen/data/tools/sc.py b/dpgen/data/tools/sc.py index fdcbe0107..c298c2cf3 100644 --- a/dpgen/data/tools/sc.py +++ b/dpgen/data/tools/sc.py @@ -12,8 +12,8 @@ def gen_box(): def poscar_unit(latt): box = gen_box() ret = "" - ret += "SC : a = %f \n" % latt - ret += "%.16f\n" % (latt) + ret += f"SC : a = {latt:f} \n" + ret += f"{latt:.16f}\n" ret += f"{box[0][0]:.16f} {box[0][1]:.16f} {box[0][2]:.16f}\n" ret += f"{box[1][0]:.16f} {box[1][1]:.16f} {box[1][2]:.16f}\n" ret += f"{box[2][0]:.16f} {box[2][1]:.16f} {box[2][2]:.16f}\n" diff --git a/dpgen/database/run.py b/dpgen/database/run.py index 2930d3f70..d2422ae14 100644 --- a/dpgen/database/run.py +++ b/dpgen/database/run.py @@ -40,7 +40,7 @@ def _main(param): skip_init = jdata["skip_init"] ## The mapping from sys_info to sys_configs assert calculator.lower() in SUPPORTED_CACULATOR - dlog.info("data collection from: %s" % path) + dlog.info(f"data collection from: {path}") if calculator == "vasp": parsing_vasp(path, config_info_dict, skip_init, output, id_prefix) elif calculator == "gaussian": @@ -53,18 +53,18 @@ def parsing_vasp(path, config_info_dict, skip_init, output=OUTPUT, id_prefix=Non fp_iters = os.path.join(path, ITERS_PAT) dlog.debug(fp_iters) f_fp_iters = glob(fp_iters) - dlog.info("len iterations data: %s" % len(f_fp_iters)) + dlog.info(f"len iterations data: {len(f_fp_iters)}") fp_init = os.path.join(path, INIT_PAT) dlog.debug(fp_init) f_fp_init = glob(fp_init) if skip_init: entries = _parsing_vasp(f_fp_iters, config_info_dict, id_prefix) - dlog.info("len collected data: %s" % len(entries)) + dlog.info(f"len collected data: {len(entries)}") else: - dlog.info("len initialization data: %s" % len(f_fp_init)) + dlog.info(f"len initialization data: {len(f_fp_init)}") entries = _parsing_vasp(f_fp_init, config_info_dict, id_prefix, iters=False) entries.extend(_parsing_vasp(f_fp_iters, config_info_dict, id_prefix)) - dlog.info("len collected data: %s" % len(entries)) + dlog.info(f"len collected data: {len(entries)}") # print(output) # print(entries) dumpfn(entries, output, indent=4) @@ -142,7 +142,7 @@ def _parsing_vasp(paths, config_info_dict, id_prefix, iters=True): icount += 1 except Exception: # dlog.info(str(Exception)) - dlog.info("failed for %s" % (path)) + dlog.info(f"failed for {path}") # pass if iters: iter_record.sort() diff --git a/dpgen/database/vasp.py b/dpgen/database/vasp.py index 7b4f94d6a..9d285e90c 100644 --- a/dpgen/database/vasp.py +++ b/dpgen/database/vasp.py @@ -50,7 +50,7 @@ def __str__(self): if self.potcars is not None: return str(self.potcars) else: - ret = "Functional: %s\n" % self.functional + ret = f"Functional: {self.functional}\n" ret += " ".join(self.symbols) + "\n" return ret diff --git a/dpgen/dispatcher/Dispatcher.py b/dpgen/dispatcher/Dispatcher.py index aad6ba6f8..08ee6474c 100644 --- a/dpgen/dispatcher/Dispatcher.py +++ b/dpgen/dispatcher/Dispatcher.py @@ -138,7 +138,7 @@ def make_submission_compat( """ if Version(api_version) < Version("1.0"): raise RuntimeError( - "API version %s has been removed. Please upgrade to 1.0." % api_version + f"API version {api_version} has been removed. Please upgrade to 1.0." ) elif Version(api_version) >= Version("1.0"): diff --git a/dpgen/generator/lib/abacus_scf.py b/dpgen/generator/lib/abacus_scf.py index 744147e88..24f59f6b4 100644 --- a/dpgen/generator/lib/abacus_scf.py +++ b/dpgen/generator/lib/abacus_scf.py @@ -35,7 +35,7 @@ def make_abacus_scf_input(fp_params, extra_file_path=""): if key == "ecutwfc": fp_params["ecutwfc"] = float(fp_params["ecutwfc"]) assert fp_params["ecutwfc"] >= 0, "'ecutwfc' should be non-negative." - ret += "ecutwfc %f\n" % fp_params["ecutwfc"] + ret += "ecutwfc {:f}\n".format(fp_params["ecutwfc"]) elif key == "kspacing": if isinstance(fp_params["kspacing"], (int, float)): fp_params["kspacing"] = [float(fp_params["kspacing"])] @@ -55,11 +55,11 @@ def make_abacus_scf_input(fp_params, extra_file_path=""): ret += "kspacing " for ikspacing in fp_params["kspacing"]: assert ikspacing >= 0, "'kspacing' should be non-negative." - ret += "%f " % ikspacing + ret += f"{ikspacing:f} " ret += "\n" elif key == "scf_thr": fp_params["scf_thr"] = float(fp_params["scf_thr"]) - ret += "scf_thr %e\n" % fp_params["scf_thr"] + ret += "scf_thr {:e}\n".format(fp_params["scf_thr"]) elif key == "scf_nmax": fp_params["scf_nmax"] = int(fp_params["scf_nmax"]) assert fp_params["scf_nmax"] >= 0 and isinstance( @@ -72,9 +72,9 @@ def make_abacus_scf_input(fp_params, extra_file_path=""): "lcao", "lcao_in_pw", ], "'basis_type' must in 'pw', 'lcao' or 'lcao_in_pw'." - ret += "basis_type %s\n" % fp_params["basis_type"] + ret += "basis_type {}\n".format(fp_params["basis_type"]) elif key == "dft_functional": - ret += "dft_functional %s\n" % fp_params["dft_functional"] + ret += "dft_functional {}\n".format(fp_params["dft_functional"]) elif key == "gamma_only": if isinstance(fp_params["gamma_only"], str): fp_params["gamma_only"] = int(eval(fp_params["gamma_only"])) @@ -90,13 +90,13 @@ def make_abacus_scf_input(fp_params, extra_file_path=""): "pulay-kerker", "broyden", ] - ret += "mixing_type %s\n" % fp_params["mixing_type"] + ret += "mixing_type {}\n".format(fp_params["mixing_type"]) elif key == "mixing_beta": fp_params["mixing_beta"] = float(fp_params["mixing_beta"]) assert ( fp_params["mixing_beta"] >= 0 and fp_params["mixing_beta"] < 1 ), "'mixing_beta' should between 0 and 1." - ret += "mixing_beta %f\n" % fp_params["mixing_beta"] + ret += "mixing_beta {:f}\n".format(fp_params["mixing_beta"]) elif key == "symmetry": if isinstance(fp_params["symmetry"], str): fp_params["symmetry"] = int(eval(fp_params["symmetry"])) @@ -130,7 +130,7 @@ def make_abacus_scf_input(fp_params, extra_file_path=""): "scalapack_gvx", ] ), "'ks_sover' should in 'cgx', 'dav', 'lapack', 'genelpa', 'hpseps', 'scalapack_gvx'." - ret += "ks_solver %s\n" % fp_params["ks_solver"] + ret += "ks_solver {}\n".format(fp_params["ks_solver"]) elif key == "smearing_method": assert ( fp_params["smearing_method"] @@ -144,13 +144,13 @@ def make_abacus_scf_input(fp_params, extra_file_path=""): "mv", ] ), "'smearing_method' should in 'gauss', 'gaussian', 'fd', 'fixed', 'mp', 'mp2', 'mv'. " - ret += "smearing_method %s\n" % fp_params["smearing_method"] + ret += "smearing_method {}\n".format(fp_params["smearing_method"]) elif key == "smearing_sigma": fp_params["smearing_sigma"] = float(fp_params["smearing_sigma"]) assert ( fp_params["smearing_sigma"] >= 0 ), "'smearing_sigma' should be non-negative." - ret += "smearing_sigma %f\n" % fp_params["smearing_sigma"] + ret += "smearing_sigma {:f}\n".format(fp_params["smearing_sigma"]) elif key == "cal_force": if isinstance(fp_params["cal_force"], str): fp_params["cal_force"] = int(eval(fp_params["cal_force"])) @@ -192,8 +192,10 @@ def make_abacus_scf_input(fp_params, extra_file_path=""): ), "'deepks_scf' should be either 0 or 1." ret += "deepks_scf %d\n" % fp_params["deepks_scf"] elif key == "deepks_model": - ret += "deepks_model %s\n" % os.path.join( - extra_file_path, os.path.split(fp_params["deepks_model"])[1] + ret += "deepks_model {}\n".format( + os.path.join( + extra_file_path, os.path.split(fp_params["deepks_model"])[1] + ) ) elif key[0] == "_": pass @@ -226,9 +228,9 @@ def make_abacus_scf_stru( ret = "ATOMIC_SPECIES\n" for iatom in range(len(atom_names)): - assert atom_names[iatom] in type_map, ( - "element %s is not defined in type_map" % atom_names[iatom] - ) + assert ( + atom_names[iatom] in type_map + ), f"element {atom_names[iatom]} is not defined in type_map" idx = type_map.index(atom_names[iatom]) if "atom_masses" not in sys_data: ret += ( @@ -240,7 +242,7 @@ def make_abacus_scf_stru( else: ret += ( atom_names[iatom] - + " %.3f " % sys_data["atom_masses"][iatom] + + " {:.3f} ".format(sys_data["atom_masses"][iatom]) + os.path.join(pporb, fp_pp_files[idx]) + "\n" ) diff --git a/dpgen/generator/lib/calypso_check_outcar.py b/dpgen/generator/lib/calypso_check_outcar.py index 668131669..fbb63994f 100644 --- a/dpgen/generator/lib/calypso_check_outcar.py +++ b/dpgen/generator/lib/calypso_check_outcar.py @@ -55,18 +55,18 @@ def Write_Outcar(element, ele, volume, lat, pos, ene, force, stress, pstress): "\nDirection XX YY ZZ XY YZ ZX\n" ) f.write("in kB") - f.write("%15.6f" % stress[0]) - f.write("%15.6f" % stress[1]) - f.write("%15.6f" % stress[2]) - f.write("%15.6f" % stress[3]) - f.write("%15.6f" % stress[4]) - f.write("%15.6f" % stress[5]) + f.write(f"{stress[0]:15.6f}") + f.write(f"{stress[1]:15.6f}") + f.write(f"{stress[2]:15.6f}") + f.write(f"{stress[3]:15.6f}") + f.write(f"{stress[4]:15.6f}") + f.write(f"{stress[5]:15.6f}") f.write("\n") ext_pressure = np.sum(stress[0] + stress[1] + stress[2]) / 3.0 - pstress f.write( f"external pressure = {ext_pressure:20.6f} kB Pullay stress = {pstress:20.6f} kB\n" ) - f.write("volume of cell : %20.6f\n" % volume) + f.write(f"volume of cell : {volume:20.6f}\n") f.write("direct lattice vectors\n") for i in range(3): f.write("{:10.6f} {:10.6f} {:10.6f}\n".format(*tuple(lat[i]))) diff --git a/dpgen/generator/lib/calypso_run_model_devi.py b/dpgen/generator/lib/calypso_run_model_devi.py index 5ad3f70bb..bb3394763 100644 --- a/dpgen/generator/lib/calypso_run_model_devi.py +++ b/dpgen/generator/lib/calypso_run_model_devi.py @@ -70,7 +70,7 @@ def Modd(all_models, type_map): new_index = 0 for index, frameid in enumerate(temp_sl): pdata = structures_data[frameid] - pdata.to_vasp_poscar(os.path.join(put_poscar, "%s.poscar" % str(index))) + pdata.to_vasp_poscar(os.path.join(put_poscar, f"{str(index)}.poscar")) nopbc = pdata.nopbc coord = pdata.data["coords"] cell = pdata.data["cells"] if not nopbc else None diff --git a/dpgen/generator/lib/calypso_run_opt.py b/dpgen/generator/lib/calypso_run_opt.py index b87abe726..49b503be4 100644 --- a/dpgen/generator/lib/calypso_run_opt.py +++ b/dpgen/generator/lib/calypso_run_opt.py @@ -60,18 +60,18 @@ def Write_Outcar(element, ele, volume, lat, pos, ene, force, stress, pstress): "\nDirection XX YY ZZ XY YZ ZX\n" ) f.write("in kB") - f.write("%15.6f" % stress[0]) - f.write("%15.6f" % stress[1]) - f.write("%15.6f" % stress[2]) - f.write("%15.6f" % stress[3]) - f.write("%15.6f" % stress[4]) - f.write("%15.6f" % stress[5]) + f.write(f"{stress[0]:15.6f}") + f.write(f"{stress[1]:15.6f}") + f.write(f"{stress[2]:15.6f}") + f.write(f"{stress[3]:15.6f}") + f.write(f"{stress[4]:15.6f}") + f.write(f"{stress[5]:15.6f}") f.write("\n") ext_pressure = np.sum(stress[0] + stress[1] + stress[2]) / 3.0 - pstress f.write( f"external pressure = {ext_pressure:20.6f} kB Pullay stress = {pstress:20.6f} kB\n" ) - f.write("volume of cell : %20.6f\n" % volume) + f.write(f"volume of cell : {volume:20.6f}\n") f.write("direct lattice vectors\n") for i in range(3): f.write("{:10.6f} {:10.6f} {:10.6f}\n".format(*tuple(lat[i]))) @@ -94,9 +94,9 @@ def read_stress_fmax(): try: f = open("input.dat") except Exception: - assert os.path.exists("../input.dat"), ( - " now we are in %s, do not find ../input.dat" % (os.getcwd()) - ) + assert os.path.exists( + "../input.dat" + ), f" now we are in {os.getcwd()}, do not find ../input.dat" f = open("../input.dat") lines = f.readlines() f.close() diff --git a/dpgen/generator/lib/lammps.py b/dpgen/generator/lib/lammps.py index d96415a3f..052b75a0f 100644 --- a/dpgen/generator/lib/lammps.py +++ b/dpgen/generator/lib/lammps.py @@ -63,16 +63,16 @@ def make_lammps_input( ret += "atom_modify map yes\n" ret += "variable THERMO_FREQ equal %d\n" % trj_freq ret += "variable DUMP_FREQ equal %d\n" % trj_freq - ret += "variable TEMP equal %f\n" % temp + ret += f"variable TEMP equal {temp:f}\n" if nbeads is not None: ret += "variable TEMP_NBEADS equal %f\n" % (temp * nbeads) if ele_temp_f is not None: - ret += "variable ELE_TEMP equal %f\n" % ele_temp_f + ret += f"variable ELE_TEMP equal {ele_temp_f:f}\n" if ele_temp_a is not None: - ret += "variable ELE_TEMP equal %f\n" % ele_temp_a - ret += "variable PRES equal %f\n" % pres - ret += "variable TAU_T equal %f\n" % tau_t - ret += "variable TAU_P equal %f\n" % tau_p + ret += f"variable ELE_TEMP equal {ele_temp_a:f}\n" + ret += f"variable PRES equal {pres:f}\n" + ret += f"variable TAU_T equal {tau_t:f}\n" + ret += f"variable TAU_P equal {tau_p:f}\n" ret += "\n" ret += "units metal\n" if nopbc: @@ -87,15 +87,9 @@ def make_lammps_input( ret += "\n" ret += "box tilt large\n" if nbeads is None: - ret += ( - 'if "${restart} > 0" then "read_restart dpgen.restart.*" else "read_data %s"\n' - % conf_file - ) + ret += f'if "${{restart}} > 0" then "read_restart dpgen.restart.*" else "read_data {conf_file}"\n' else: - ret += ( - 'if "${restart} > 0" then "read_restart dpgen.restart${ibead}.*" else "read_data %s"\n' - % conf_file - ) + ret += f'if "${{restart}} > 0" then "read_restart dpgen.restart${{ibead}}.*" else "read_data {conf_file}"\n' ret += "change_box all triclinic\n" for jj in range(len(mass_map)): ret += "mass %d %f\n" % (jj + 1, mass_map[jj]) @@ -104,16 +98,16 @@ def make_lammps_input( graph_list += ii + " " if Version(deepmd_version) < Version("1"): # 0.x - ret += "pair_style deepmd %s ${THERMO_FREQ} model_devi.out\n" % graph_list + ret += f"pair_style deepmd {graph_list} ${{THERMO_FREQ}} model_devi.out\n" else: # 1.x keywords = "" if jdata.get("use_clusters", False): keywords += "atomic " if jdata.get("use_relative", False): - keywords += "relative %s " % jdata["epsilon"] + keywords += "relative {} ".format(jdata["epsilon"]) if jdata.get("use_relative_v", False): - keywords += "relative_v %s " % jdata["epsilon_v"] + keywords += "relative_v {} ".format(jdata["epsilon_v"]) if ele_temp_f is not None: keywords += "fparam ${ELE_TEMP}" if ele_temp_a is not None: @@ -175,7 +169,7 @@ def make_lammps_input( if ensemble.split("-")[0] == "npt": assert pres is not None if nopbc: - raise RuntimeError("ensemble %s is conflicting with nopbc" % ensemble) + raise RuntimeError(f"ensemble {ensemble} is conflicting with nopbc") if nbeads is None: if ensemble == "npt" or ensemble == "npt-i" or ensemble == "npt-iso": ret += "fix 1 all npt temp ${TEMP} ${TEMP} ${TAU_T} iso ${PRES} ${PRES} ${TAU_P}\n" @@ -208,7 +202,7 @@ def make_lammps_input( ret += "velocity all zero linear\n" ret += "fix fm all momentum 1 linear 1 1 1\n" ret += "\n" - ret += "timestep %f\n" % dt + ret += f"timestep {dt:f}\n" ret += "run ${NSTEPS} upto\n" return ret diff --git a/dpgen/generator/lib/make_calypso.py b/dpgen/generator/lib/make_calypso.py index c96e2e960..59e4f263d 100644 --- a/dpgen/generator/lib/make_calypso.py +++ b/dpgen/generator/lib/make_calypso.py @@ -27,26 +27,26 @@ def make_calypso_input( ret = "################################ The Basic Parameters of CALYPSO ################################\n" ret += "# A string of one or several words contain a descriptive name of the system (max. 40 characters).\n" assert nameofatoms is not None - ret += "SystemName = %s\n" % ("".join(nameofatoms)) + ret += "SystemName = {}\n".format("".join(nameofatoms)) ret += "# Number of different atomic species in the simulation.\n" ret += "NumberOfSpecies = %d\n" % (len(nameofatoms)) ret += "# Element symbols of the different chemical species.\n" - ret += "NameOfAtoms = %s\n" % (" ".join(nameofatoms)) + ret += "NameOfAtoms = {}\n".format(" ".join(nameofatoms)) ret += "# Number of atoms for each chemical species in one formula unit. \n" assert numberofatoms is not None and len(numberofatoms) == len(nameofatoms) - ret += "NumberOfAtoms = %s\n" % (" ".join(list(map(str, numberofatoms)))) + ret += "NumberOfAtoms = {}\n".format(" ".join(list(map(str, numberofatoms)))) ret += "# The range of formula unit per cell in your simulation. \n" assert ( numberofformula is not None and len(numberofformula) == 2 and isinstance(numberofformula, list) ) - ret += "NumberOfFormula = %s\n" % (" ".join(list(map(str, numberofformula)))) + ret += "NumberOfFormula = {}\n".format(" ".join(list(map(str, numberofformula)))) ret += "# The volume per formula unit. Unit is in angstrom^3.\n" if volume is None: ret += "# volume not found, CALYPSO will set one!\n" else: - ret += "Volume = %s\n" % (volume) + ret += f"Volume = {volume}\n" ret += "# Minimal distance between atoms of each chemical species. Unit is in angstrom.\n" assert len(distanceofion) == len( nameofatoms @@ -62,7 +62,7 @@ def make_calypso_input( ret += "# Ialgo = 2 for Local PSO (default value)\n" ret += "# The proportion of the structures generated by PSO.\n" assert 0 <= psoratio <= 1 - ret += "PsoRatio = %s\n" % (psoratio) + ret += f"PsoRatio = {psoratio}\n" ret += ( "# The population size. Normally, it has a larger number for larger systems.\n" ) @@ -100,13 +100,13 @@ def make_calypso_input( ret += "# The number node for parallel \n" ret += "NumberOfParallel = 4\n" assert split is not None - ret += "Split = %s\n" % (split) + ret += f"Split = {split}\n" assert pstress is not None and ( isinstance(pstress, int) or isinstance(pstress, float) ) - ret += "PSTRESS = %f\n" % (pstress) + ret += f"PSTRESS = {pstress:f}\n" assert fmax is not None or isinstance(fmax, float) - ret += "fmax = %f\n" % (fmax) + ret += f"fmax = {fmax:f}\n" ret += "################################ End of The Basic Parameters of CALYPSO #######################\n" if vsc == "T": assert len(ctrlrange) == len( @@ -116,9 +116,9 @@ def make_calypso_input( ret += ( "## If True, Variational Stoichiometry structure prediction is performed\n" ) - ret += "VSC = %s\n" % (vsc) + ret += f"VSC = {vsc}\n" ret += "# The Max Number of Atoms in unit cell\n" - ret += "MaxNumAtom = %s\n" % (maxnumatom) + ret += f"MaxNumAtom = {maxnumatom}\n" ret += "# The Variation Range for each type atom \n" ret += "@CtrlRange\n" for ttemp in ctrlrange: diff --git a/dpgen/generator/lib/pwscf.py b/dpgen/generator/lib/pwscf.py index ebd8a2dc0..ffbf19a44 100644 --- a/dpgen/generator/lib/pwscf.py +++ b/dpgen/generator/lib/pwscf.py @@ -58,19 +58,19 @@ def _make_pwscf_01_runctrl(sys_data, ecut, ediff, smearing, degauss): ret += "/\n" ret += "&system\n" ret += "vdw_corr='TS',\n" - ret += "ecutwfc=%s,\n" % str(ecut) - ret += "ts_vdw_econv_thr=%s,\n" % str(ediff) + ret += f"ecutwfc={str(ecut)},\n" + ret += f"ts_vdw_econv_thr={str(ediff)},\n" ret += "nosym=.TRUE.,\n" ret += "ibrav=0,\n" ret += "nat=%d,\n" % tot_natoms ret += "ntyp=%d,\n" % ntypes if degauss is not None: - ret += "degauss=%f,\n" % degauss + ret += f"degauss={degauss:f},\n" if smearing is not None: - ret += "smearing='%s',\n" % (smearing.lower()) + ret += f"smearing='{smearing.lower()}',\n" ret += "/\n" ret += "&electrons\n" - ret += "conv_thr=%s,\n" % str(ediff) + ret += f"conv_thr={str(ediff)},\n" ret += "/\n" return ret @@ -103,7 +103,7 @@ def _make_pwscf_03_config(sys_data): ret += "CELL_PARAMETERS { angstrom }\n" for ii in range(3): for jj in range(3): - ret += "%f " % cell[ii][jj] + ret += f"{cell[ii][jj]:f} " ret += "\n" ret += "\n" ret += "ATOMIC_POSITIONS { angstrom }\n" diff --git a/dpgen/generator/lib/run_calypso.py b/dpgen/generator/lib/run_calypso.py index 6af12008d..0e4744471 100644 --- a/dpgen/generator/lib/run_calypso.py +++ b/dpgen/generator/lib/run_calypso.py @@ -54,12 +54,12 @@ def gen_structures( model_names = [os.path.basename(ii) for ii in all_models] deepmdkit_python = mdata.get("model_devi_deepmdkit_python") - command = "%s calypso_run_opt.py 1>> model_devi.log 2>> model_devi.log" % ( - deepmdkit_python + command = ( + f"{deepmdkit_python} calypso_run_opt.py 1>> model_devi.log 2>> model_devi.log" ) # command = "%s calypso_run_opt.py %s 1>> model_devi.log 2>> model_devi.log" % (deepmdkit_python,os.path.abspath(calypso_run_opt_path)) # command += " || %s check_outcar.py %s " % (deepmdkit_python,os.path.abspath(calypso_run_opt_path)) - command += " || %s check_outcar.py " % (deepmdkit_python) + command += f" || {deepmdkit_python} check_outcar.py " commands = [command] cwd = os.getcwd() @@ -72,11 +72,11 @@ def gen_structures( if not vsc: Lpickup = _parse_calypso_input("PickUp", ".") PickUpStep = _parse_calypso_input("PickStep", ".") - if os.path.exists("tag_pickup_%s" % (str(PickUpStep))): - dlog.info("caution! tag_pickup_%s exists!" % str(PickUpStep)) + if os.path.exists(f"tag_pickup_{str(PickUpStep)}"): + dlog.info(f"caution! tag_pickup_{str(PickUpStep)} exists!") Lpickup = "F" if Lpickup == "T": - ftag = open("tag_pickup_%s" % (str(PickUpStep)), "w") + ftag = open(f"tag_pickup_{str(PickUpStep)}", "w") ftag.close() os.remove("step") fstep = open("step", "w") @@ -93,13 +93,13 @@ def gen_structures( maxstep = int(_parse_calypso_input("MaxStep", ".")) for ii in range(int(PickUpStep) - 1, maxstep + 1): - dlog.info("CALYPSO step %s" % ii) + dlog.info(f"CALYPSO step {ii}") if ii == maxstep: - os.system("%s" % run_calypso) + os.system(f"{run_calypso}") break # run calypso - os.system("%s" % (run_calypso)) + os.system(f"{run_calypso}") for pop in range(ii * int(popsize), (ii + 1) * int(popsize)): try: @@ -116,7 +116,7 @@ def gen_structures( os.path.join("task.%03d" % pop, "check_outcar.py"), ) shutil.copyfile( - "POSCAR_%s" % str(pop - ii * int(popsize) + 1), + f"POSCAR_{str(pop - ii * int(popsize) + 1)}", os.path.join("task.%03d" % (pop), "POSCAR"), ) shutil.copyfile( @@ -134,8 +134,7 @@ def gen_structures( if Version(api_version) < Version("1.0"): raise RuntimeError( - "API version %s has been removed. Please upgrade to 1.0." - % api_version + f"API version {api_version} has been removed. Please upgrade to 1.0." ) elif Version(api_version) >= Version("1.0"): os.chdir(cwd) @@ -163,32 +162,30 @@ def gen_structures( for jjj in range(ii * int(popsize), (ii + 1) * int(popsize)): # to opt directory shutil.copyfile( - "POSCAR_%s" % str(jjj + 1 - ii * int(popsize)), - os.path.join(sstep, "POSCAR_%s" % str(jjj + 1 - ii * int(popsize))), + f"POSCAR_{str(jjj + 1 - ii * int(popsize))}", + os.path.join(sstep, f"POSCAR_{str(jjj + 1 - ii * int(popsize))}"), ) shutil.copyfile( os.path.join("task.%03d" % (jjj), "OUTCAR"), - os.path.join(sstep, "OUTCAR_%s" % str(jjj + 1 - ii * int(popsize))), + os.path.join(sstep, f"OUTCAR_{str(jjj + 1 - ii * int(popsize))}"), ) shutil.copyfile( os.path.join("task.%03d" % (jjj), "CONTCAR"), - os.path.join( - sstep, "CONTCAR_%s" % str(jjj + 1 - ii * int(popsize)) - ), + os.path.join(sstep, f"CONTCAR_{str(jjj + 1 - ii * int(popsize))}"), ) # to run calypso directory shutil.copyfile( os.path.join("task.%03d" % (jjj), "OUTCAR"), - "OUTCAR_%s" % str(jjj + 1 - ii * int(popsize)), + f"OUTCAR_{str(jjj + 1 - ii * int(popsize))}", ) shutil.copyfile( os.path.join("task.%03d" % (jjj), "CONTCAR"), - "CONTCAR_%s" % str(jjj + 1 - ii * int(popsize)), + f"CONTCAR_{str(jjj + 1 - ii * int(popsize))}", ) # to traj shutil.copyfile( os.path.join("task.%03d" % (jjj), "traj.traj"), - os.path.join("traj", "%s.traj" % str(jjj + 1)), + os.path.join("traj", f"{str(jjj + 1)}.traj"), ) tlist = glob.glob("task.*") @@ -224,12 +221,12 @@ def gen_structures( if not os.path.exists(com): os.mkdir(com) # shutil.copyfile(os.path.join(calypso_input_path,'input.dat.%s'%com),os.path.join(com,'input.dat')) - shutil.copyfile("input.dat.%s" % com, os.path.join(com, "input.dat")) + shutil.copyfile(f"input.dat.{com}", os.path.join(com, "input.dat")) os.chdir(com) os.system(run_calypso) os.chdir(pwd) - shutil.copyfile("input.dat.%s" % component[-1], "input.dat") + shutil.copyfile(f"input.dat.{component[-1]}", "input.dat") name_list = Path(".").glob("*/POSCAR_*") for idx, name in enumerate(name_list): @@ -248,7 +245,7 @@ def gen_structures( os.path.join("task.%04d" % (idx + 1), "check_outcar.py"), ) shutil.copyfile( - "POSCAR_%s" % str(idx + 1), + f"POSCAR_{str(idx + 1)}", os.path.join("task.%04d" % (idx + 1), "POSCAR"), ) shutil.copyfile( @@ -266,7 +263,7 @@ def gen_structures( if Version(api_version) < Version("1.0"): raise RuntimeError( - "API version %s has been removed. Please upgrade to 1.0." % api_version + f"API version {api_version} has been removed. Please upgrade to 1.0." ) elif Version(api_version) >= Version("1.0"): os.chdir(cwd) @@ -292,30 +289,30 @@ def gen_structures( for jjj in range(len(all_task)): # to opt directory shutil.copyfile( - "POSCAR_%s" % str(jjj + 1), - os.path.join("opt", "POSCAR_%s" % str(jjj + 1)), + f"POSCAR_{str(jjj + 1)}", + os.path.join("opt", f"POSCAR_{str(jjj + 1)}"), ) shutil.copyfile( os.path.join("task.%04d" % (jjj + 1), "OUTCAR"), - os.path.join("opt", "OUTCAR_%s" % str(jjj + 1)), + os.path.join("opt", f"OUTCAR_{str(jjj + 1)}"), ) shutil.copyfile( os.path.join("task.%04d" % (jjj + 1), "CONTCAR"), - os.path.join("opt", "CONTCAR_%s" % str(jjj + 1)), + os.path.join("opt", f"CONTCAR_{str(jjj + 1)}"), ) # to run calypso directory shutil.copyfile( os.path.join("task.%04d" % (jjj + 1), "OUTCAR"), - "OUTCAR_%s" % str(jjj + 1), + f"OUTCAR_{str(jjj + 1)}", ) shutil.copyfile( os.path.join("task.%04d" % (jjj + 1), "CONTCAR"), - "CONTCAR_%s" % str(jjj + 1), + f"CONTCAR_{str(jjj + 1)}", ) # to traj shutil.copyfile( os.path.join("task.%04d" % (jjj + 1), "traj.traj"), - os.path.join("traj", "%s.traj" % str(jjj + 1)), + os.path.join("traj", f"{str(jjj + 1)}.traj"), ) tlist = glob.glob("task.*") @@ -324,7 +321,7 @@ def gen_structures( # -------------------------------------------------------------- if current_idx < length_of_caly_runopt_list - 1: - tobewrite = "1 %s\n" % (str(current_idx + 1)) + tobewrite = f"1 {str(current_idx + 1)}\n" elif current_idx == length_of_caly_runopt_list - 1: tobewrite = "2\n" @@ -458,7 +455,7 @@ def run_calypso_model_devi(iter_index, jdata, mdata): calypso_model_devi_path = os.path.join(work_path, calypso_model_devi_name) _caly_run_opt_list = glob.glob( - os.path.join(work_path, "%s.*" % (str(calypso_run_opt_name))) + os.path.join(work_path, f"{str(calypso_run_opt_name)}.*") ) caly_run_opt_list = _caly_run_opt_list.copy() # check if gen_struc_analy.000.bk000 in caly_run_opt_list diff --git a/dpgen/generator/lib/siesta.py b/dpgen/generator/lib/siesta.py index 0c7faabc9..d0277347c 100644 --- a/dpgen/generator/lib/siesta.py +++ b/dpgen/generator/lib/siesta.py @@ -20,14 +20,14 @@ def _make_siesta_01_common(sys_data, fp_params): if "ecut" in fp_params.keys(): ecut = fp_params["ecut"] - ret += "MeshCutoff %s" % str(ecut) + ret += f"MeshCutoff {str(ecut)}" ret += " Ry\n" if "ediff" in fp_params.keys(): ediff = fp_params["ediff"] - ret += "DM.Tolerance %e\n" % ediff + ret += f"DM.Tolerance {ediff:e}\n" if "mixWeight" in fp_params.keys(): mixingWeight = fp_params["mixingWeight"] - ret += "DM.MixingWeight %f\n" % mixingWeight + ret += f"DM.MixingWeight {mixingWeight:f}\n" if "NumberPulay" in fp_params.keys(): NumberPulay = fp_params["NumberPulay"] ret += "DM.NumberPulay %d\n" % NumberPulay @@ -108,7 +108,7 @@ def _make_siesta_04_ucVectorCoord(sys_data): ret += "%block LatticeVectors\n" for ii in range(3): for jj in range(3): - ret += "%f " % cell[ii][jj] + ret += f"{cell[ii][jj]:f} " ret += "\n" ret += "%endblock LatticeVectors\n" diff --git a/dpgen/generator/lib/vasp.py b/dpgen/generator/lib/vasp.py index a5f1e7aee..7defe4dc3 100644 --- a/dpgen/generator/lib/vasp.py +++ b/dpgen/generator/lib/vasp.py @@ -90,7 +90,7 @@ def _make_smearing(fp_params): elif smearing_method == "fd": return -1, sigma else: - raise RuntimeError("unsuppported smearing method %s " % smearing_method) + raise RuntimeError(f"unsuppported smearing method {smearing_method} ") def _make_metagga(fp_params): diff --git a/dpgen/generator/run.py b/dpgen/generator/run.py index 7a4006faa..491647d98 100644 --- a/dpgen/generator/run.py +++ b/dpgen/generator/run.py @@ -305,8 +305,7 @@ def make_train(iter_index, jdata, mdata): new_to_old_ratio = float(s[1]) else: raise ValueError( - "training_reuse_old_ratio is not correct, got %s" - % training_reuse_old_ratio + f"training_reuse_old_ratio is not correct, got {training_reuse_old_ratio}" ) dlog.info( "Use automatic training_reuse_old_ratio to make new-to-old ratio close to %d times of the default value.", @@ -518,7 +517,7 @@ def make_train(iter_index, jdata, mdata): ) else: raise RuntimeError( - "Unsupported DeePMD-kit version: %s" % mdata["deepmd_version"] + "Unsupported DeePMD-kit version: {}".format(mdata["deepmd_version"]) ) if ( jinput["loss"].get("start_pref_e") is not None @@ -767,12 +766,12 @@ def run_train(iter_index, jdata, mdata): init_flag = " --finetune old/init.pb" command = f"{train_command} train {train_input_file}{extra_flags}" command = f"{{ if [ ! -f model.ckpt.index ]; then {command}{init_flag}; else {command} --restart model.ckpt; fi }}" - command = "/bin/sh -c %s" % shlex.quote(command) + command = f"/bin/sh -c {shlex.quote(command)}" commands.append(command) - command = "%s freeze" % train_command + command = f"{train_command} freeze" commands.append(command) if jdata.get("dp_compress", False): - commands.append("%s compress" % train_command) + commands.append(f"{train_command} compress") else: raise RuntimeError( "DP-GEN currently only supports for DeePMD-kit 1.x or 2.x version!" @@ -848,7 +847,7 @@ def run_train(iter_index, jdata, mdata): backward_files += mdata.get("train" + "_user_backward_files", []) if Version(api_version) < Version("1.0"): raise RuntimeError( - "API version %s has been removed. Please upgrade to 1.0." % api_version + f"API version {api_version} has been removed. Please upgrade to 1.0." ) elif Version(api_version) >= Version("1.0"): @@ -1001,7 +1000,7 @@ def find_only_one_key(lmp_lines, key): if len(found) > 1: raise RuntimeError("found %d keywords %s" % (len(found), key)) if len(found) == 0: - raise RuntimeError("failed to find keyword %s" % (key)) + raise RuntimeError(f"failed to find keyword {key}") return found[0] @@ -1114,8 +1113,7 @@ def make_model_devi(iter_index, jdata, mdata): ii_systems = sorted(glob.glob(ii)) if ii_systems == []: warnings.warn( - "There is no system in the path %s. Please check if the path is correct." - % ii + f"There is no system in the path {ii}. Please check if the path is correct." ) cur_systems += ii_systems # cur_systems should not be sorted, as we may add specific constrict to the similutions @@ -1947,7 +1945,7 @@ def run_md_model_devi(iter_index, jdata, mdata): command = f"{{ if [ ! -f dpgen.restart.10000 ]; then {model_devi_exec} -i input.lammps -v restart 0; else {model_devi_exec} -i input.lammps -v restart 1; fi }}" else: command = f"{{ all_exist=true; for i in $(seq -w 1 {nbeads}); do [[ ! -f dpgen.restart${{i}}.10000 ]] && {{ all_exist=false; break; }}; done; $all_exist && {{ {model_devi_exec} -p {nbeads}x1 -i input.lammps -v restart 1; }} || {{ {model_devi_exec} -p {nbeads}x1 -i input.lammps -v restart 0; }} }}" - command = "/bin/bash -c %s" % shlex.quote(command) + command = f"/bin/bash -c {shlex.quote(command)}" commands = [command] forward_files = ["conf.lmp", "input.lammps"] @@ -2020,8 +2018,8 @@ def run_md_model_devi(iter_index, jdata, mdata): if ndx_filename: forward_files.append(ndx_filename) backward_files = [ - "%s.tpr" % deffnm, - "%s.log" % deffnm, + f"{deffnm}.tpr", + f"{deffnm}.log", traj_filename, "model_devi.out", "traj", @@ -2055,7 +2053,7 @@ def run_md_model_devi(iter_index, jdata, mdata): ) if Version(api_version) < Version("1.0"): raise RuntimeError( - "API version %s has been removed. Please upgrade to 1.0." % api_version + f"API version {api_version} has been removed. Please upgrade to 1.0." ) elif Version(api_version) >= Version("1.0"): @@ -2662,17 +2660,17 @@ def _trust_limitation_check(sys_idx, lim): random.shuffle(fp_rest_failed) random.shuffle(fp_rest_accurate) with open( - os.path.join(work_path, "candidate.shuffled.%s.out" % ss), "w" + os.path.join(work_path, f"candidate.shuffled.{ss}.out"), "w" ) as fp: for ii in fp_candidate: fp.write(" ".join([str(nn) for nn in ii]) + "\n") with open( - os.path.join(work_path, "rest_accurate.shuffled.%s.out" % ss), "w" + os.path.join(work_path, f"rest_accurate.shuffled.{ss}.out"), "w" ) as fp: for ii in fp_rest_accurate: fp.write(" ".join([str(nn) for nn in ii]) + "\n") with open( - os.path.join(work_path, "rest_failed.shuffled.%s.out" % ss), "w" + os.path.join(work_path, f"rest_failed.shuffled.{ss}.out"), "w" ) as fp: for ii in fp_rest_failed: fp.write(" ".join([str(nn) for nn in ii]) + "\n") @@ -3177,22 +3175,22 @@ def sys_link_fp_vasp_pp(iter_index, jdata): system_idx_str.sort() for ii in system_idx_str: potcars = [] - sys_tasks = glob.glob(os.path.join(work_path, "task.%s.*" % ii)) + sys_tasks = glob.glob(os.path.join(work_path, f"task.{ii}.*")) assert len(sys_tasks) != 0 sys_poscar = os.path.join(sys_tasks[0], "POSCAR") sys = dpdata.System(sys_poscar, fmt="vasp/poscar") for ele_name in sys["atom_names"]: ele_idx = jdata["type_map"].index(ele_name) potcars.append(fp_pp_files[ele_idx]) - with open(os.path.join(work_path, "POTCAR.%s" % ii), "w") as fp_pot: + with open(os.path.join(work_path, f"POTCAR.{ii}"), "w") as fp_pot: for jj in potcars: with open(os.path.join(fp_pp_path, jj)) as fp: fp_pot.write(fp.read()) - sys_tasks = glob.glob(os.path.join(work_path, "task.%s.*" % ii)) + sys_tasks = glob.glob(os.path.join(work_path, f"task.{ii}.*")) cwd = os.getcwd() for jj in sys_tasks: os.chdir(jj) - os.symlink(os.path.join("..", "POTCAR.%s" % ii), "POTCAR") + os.symlink(os.path.join("..", f"POTCAR.{ii}"), "POTCAR") os.chdir(cwd) @@ -3244,7 +3242,7 @@ def _link_fp_abacus_pporb_descript(iter_index, jdata): type_map_idx = type_map.index(iatom) if iatom not in type_map: raise RuntimeError( - "atom name %s in STRU is not defined in type_map" % (iatom) + f"atom name {iatom} in STRU is not defined in type_map" ) if pp_files_stru: src_file = os.path.join(fp_pp_path, jdata["fp_pp_files"][type_map_idx]) @@ -3925,7 +3923,7 @@ def run_fp_inner( api_version = mdata.get("api_version", "1.0") if Version(api_version) < Version("1.0"): raise RuntimeError( - "API version %s has been removed. Please upgrade to 1.0." % api_version + f"API version {api_version} has been removed. Please upgrade to 1.0." ) elif Version(api_version) >= Version("1.0"): @@ -4154,7 +4152,7 @@ def post_fp_vasp(iter_index, jdata, rfailed=None): tcount = 0 icount = 0 for ss in system_index: - sys_outcars = glob.glob(os.path.join(work_path, "task.%s.*/OUTCAR" % ss)) + sys_outcars = glob.glob(os.path.join(work_path, f"task.{ss}.*/OUTCAR")) sys_outcars.sort() tcount += len(sys_outcars) all_sys = None @@ -4170,7 +4168,7 @@ def post_fp_vasp(iter_index, jdata, rfailed=None): ) except Exception: _sys = dpdata.LabeledSystem() - dlog.info("Failed fp path: %s" % oo.replace("OUTCAR", "")) + dlog.info("Failed fp path: {}".format(oo.replace("OUTCAR", ""))) if len(_sys) == 1: # save ele_temp, if any if os.path.exists(oo.replace("OUTCAR", "job.json")): @@ -4207,7 +4205,7 @@ def post_fp_vasp(iter_index, jdata, rfailed=None): icount += 1 all_te = np.array(all_te) if all_sys is not None: - sys_data_path = os.path.join(work_path, "data.%s" % ss) + sys_data_path = os.path.join(work_path, f"data.{ss}") all_sys.to_deepmd_raw(sys_data_path) all_sys.to_deepmd_npy(sys_data_path, set_size=len(sys_outcars)) @@ -4247,8 +4245,8 @@ def post_fp_pwscf(iter_index, jdata): cwd = os.getcwd() for ss in system_index: - sys_output = glob.glob(os.path.join(work_path, "task.%s.*/output" % ss)) - sys_input = glob.glob(os.path.join(work_path, "task.%s.*/input" % ss)) + sys_output = glob.glob(os.path.join(work_path, f"task.{ss}.*/output")) + sys_input = glob.glob(os.path.join(work_path, f"task.{ss}.*/input")) sys_output.sort() sys_input.sort() @@ -4270,7 +4268,7 @@ def post_fp_pwscf(iter_index, jdata): if len(_sys) > 0: all_sys.append(_sys) - sys_data_path = os.path.join(work_path, "data.%s" % ss) + sys_data_path = os.path.join(work_path, f"data.{ss}") all_sys.to_deepmd_raw(sys_data_path) all_sys.to_deepmd_npy(sys_data_path, set_size=len(sys_output)) @@ -4296,8 +4294,8 @@ def post_fp_abacus_scf(iter_index, jdata): cwd = os.getcwd() for ss in system_index: - sys_output = glob.glob(os.path.join(work_path, "task.%s.*" % ss)) - sys_input = glob.glob(os.path.join(work_path, "task.%s.*/INPUT" % ss)) + sys_output = glob.glob(os.path.join(work_path, f"task.{ss}.*")) + sys_input = glob.glob(os.path.join(work_path, f"task.{ss}.*/INPUT")) sys_output.sort() sys_input.sort() @@ -4313,7 +4311,7 @@ def post_fp_abacus_scf(iter_index, jdata): all_sys.append(_sys) if all_sys is not None: - sys_data_path = os.path.join(work_path, "data.%s" % ss) + sys_data_path = os.path.join(work_path, f"data.{ss}") all_sys.to_deepmd_raw(sys_data_path) all_sys.to_deepmd_npy(sys_data_path, set_size=len(sys_output)) @@ -4339,8 +4337,8 @@ def post_fp_siesta(iter_index, jdata): cwd = os.getcwd() for ss in system_index: - sys_output = glob.glob(os.path.join(work_path, "task.%s.*/output" % ss)) - sys_input = glob.glob(os.path.join(work_path, "task.%s.*/input" % ss)) + sys_output = glob.glob(os.path.join(work_path, f"task.{ss}.*/output")) + sys_input = glob.glob(os.path.join(work_path, f"task.{ss}.*/input")) sys_output.sort() sys_input.sort() for idx, oo in enumerate(sys_output): @@ -4360,7 +4358,7 @@ def post_fp_siesta(iter_index, jdata): else: all_sys.append(_sys) - sys_data_path = os.path.join(work_path, "data.%s" % ss) + sys_data_path = os.path.join(work_path, f"data.{ss}") all_sys.to_deepmd_raw(sys_data_path) all_sys.to_deepmd_npy(sys_data_path, set_size=len(sys_output)) @@ -4386,7 +4384,7 @@ def post_fp_gaussian(iter_index, jdata): cwd = os.getcwd() for ss in system_index: - sys_output = glob.glob(os.path.join(work_path, "task.%s.*/output" % ss)) + sys_output = glob.glob(os.path.join(work_path, f"task.{ss}.*/output")) sys_output.sort() for idx, oo in enumerate(sys_output): sys = dpdata.LabeledSystem(oo, fmt="gaussian/log") @@ -4403,7 +4401,7 @@ def post_fp_gaussian(iter_index, jdata): all_sys = sys else: all_sys.append(sys) - sys_data_path = os.path.join(work_path, "data.%s" % ss) + sys_data_path = os.path.join(work_path, f"data.{ss}") all_sys.to_deepmd_raw(sys_data_path) all_sys.to_deepmd_npy(sys_data_path, set_size=len(sys_output)) @@ -4434,7 +4432,7 @@ def post_fp_cp2k(iter_index, jdata, rfailed=None): # icount: num of converged fp tasks icount = 0 for ss in system_index: - sys_output = glob.glob(os.path.join(work_path, "task.%s.*/output" % ss)) + sys_output = glob.glob(os.path.join(work_path, f"task.{ss}.*/output")) sys_output.sort() tcount += len(sys_output) all_sys = dpdata.MultiSystems(type_map=jdata["type_map"]) @@ -4446,7 +4444,7 @@ def post_fp_cp2k(iter_index, jdata, rfailed=None): icount += 1 if (all_sys is not None) and (len(all_sys) > 0): - sys_data_path = os.path.join(work_path, "data.%s" % ss) + sys_data_path = os.path.join(work_path, f"data.{ss}") all_sys.to_deepmd_raw(sys_data_path) all_sys.to_deepmd_npy(sys_data_path) @@ -4491,7 +4489,7 @@ def post_fp_pwmat(iter_index, jdata, rfailed=None): tcount = 0 icount = 0 for ss in system_index: - sys_output = glob.glob(os.path.join(work_path, "task.%s.*/OUT.MLMD" % ss)) + sys_output = glob.glob(os.path.join(work_path, f"task.{ss}.*/OUT.MLMD")) sys_output.sort() tcount += len(sys_output) all_sys = None @@ -4505,11 +4503,11 @@ def post_fp_pwmat(iter_index, jdata, rfailed=None): else: icount += 1 if all_sys is not None: - sys_data_path = os.path.join(work_path, "data.%s" % ss) + sys_data_path = os.path.join(work_path, f"data.{ss}") all_sys.to_deepmd_raw(sys_data_path) all_sys.to_deepmd_npy(sys_data_path, set_size=len(sys_output)) - dlog.info("failed frame number: %s " % icount) - dlog.info("total frame number: %s " % tcount) + dlog.info(f"failed frame number: {icount} ") + dlog.info(f"total frame number: {tcount} ") reff = icount / tcount dlog.info(f"ratio of failed frame: {reff:.2%}") @@ -4537,7 +4535,7 @@ def post_fp_amber_diff(iter_index, jdata): system_index.sort() for ss in system_index: - sys_output = glob.glob(os.path.join(work_path, "task.%s.*" % ss)) + sys_output = glob.glob(os.path.join(work_path, f"task.{ss}.*")) sys_output.sort() all_sys = dpdata.MultiSystems(type_map=jdata["type_map"]) for oo in sys_output: @@ -4545,7 +4543,7 @@ def post_fp_amber_diff(iter_index, jdata): os.path.join(oo, "dataset") ) all_sys.append(sys) - sys_data_path = os.path.join(work_path, "data.%s" % ss) + sys_data_path = os.path.join(work_path, f"data.{ss}") all_sys.to_deepmd_raw(sys_data_path) all_sys.to_deepmd_npy(sys_data_path, set_size=len(sys_output), prec=np.float64) @@ -4583,14 +4581,14 @@ def post_fp_custom(iter_index, jdata): output_fmt = fp_params["output_fmt"] for ss in system_index: - sys_output = glob.glob(os.path.join(work_path, "task.%s.*" % ss)) + sys_output = glob.glob(os.path.join(work_path, f"task.{ss}.*")) sys_output.sort() all_sys = dpdata.MultiSystems(type_map=jdata["type_map"]) for oo in sys_output: if os.path.exists(os.path.join(oo, output_fn)): sys = dpdata.LabeledSystem(os.path.join(oo, output_fn), fmt=output_fmt) all_sys.append(sys) - sys_data_path = os.path.join(work_path, "data.%s" % ss) + sys_data_path = os.path.join(work_path, f"data.{ss}") all_sys.to_deepmd_raw(sys_data_path) all_sys.to_deepmd_npy(sys_data_path, set_size=len(sys_output), prec=np.float64) diff --git a/dpgen/remote/decide_machine.py b/dpgen/remote/decide_machine.py index e76c61e2d..e4f04b4ad 100644 --- a/dpgen/remote/decide_machine.py +++ b/dpgen/remote/decide_machine.py @@ -29,7 +29,7 @@ def convert_mdata(mdata, task_types=["train", "model_devi", "fp"]): elif isinstance(mdata[task_type], (list, tuple)): task_data = mdata[task_type][0] else: - raise TypeError("mdata/%s should be dict or list!" % task_type) + raise TypeError(f"mdata/{task_type} should be dict or list!") for key, item in task_data.items(): if "comments" not in key: mdata[task_type + "_" + key] = item diff --git a/dpgen/simplify/simplify.py b/dpgen/simplify/simplify.py index eec08e8bf..7ad08dc77 100644 --- a/dpgen/simplify/simplify.py +++ b/dpgen/simplify/simplify.py @@ -255,7 +255,7 @@ def run_model_devi(iter_index, jdata, mdata): api_version = mdata.get("api_version", "1.0") if Version(api_version) < Version("1.0"): raise RuntimeError( - "API version %s has been removed. Please upgrade to 1.0." % api_version + f"API version {api_version} has been removed. Please upgrade to 1.0." ) elif Version(api_version) >= Version("1.0"): diff --git a/dpgen/tools/relabel.py b/dpgen/tools/relabel.py index 140e614fa..9b64a3edd 100755 --- a/dpgen/tools/relabel.py +++ b/dpgen/tools/relabel.py @@ -248,7 +248,7 @@ def create_tasks( print("# working on " + sys_dir) for tt, rr in zip(sys_tasks[si], sys_tasks_record[si]): # copy poscar - source_path = os.path.join(("iter.%s/02.fp" % rr.split()[1]), rr.split()[9]) + source_path = os.path.join((f"iter.{rr.split()[1]}/02.fp"), rr.split()[9]) source_file = os.path.join(source_path, "POSCAR") target_path = os.path.join(sys_dir, "task.%06d" % sys_tasks_cc[si]) sys_tasks_cc[si] += 1 diff --git a/dpgen/util.py b/dpgen/util.py index cd38d1473..73453d74b 100644 --- a/dpgen/util.py +++ b/dpgen/util.py @@ -74,7 +74,7 @@ def expand_sys_str(root_dir: Union[str, Path]) -> list[str]: else: raise OSError(f"{root_dir} does not exist.") if len(matches) == 0: - raise RuntimeError("%s does not contain any systems!" % root_dir) + raise RuntimeError(f"{root_dir} does not contain any systems!") return matches diff --git a/tests/generator/test_make_fp.py b/tests/generator/test_make_fp.py index e22199569..aa01ab5f1 100644 --- a/tests/generator/test_make_fp.py +++ b/tests/generator/test_make_fp.py @@ -519,7 +519,7 @@ def _check_incar_ele_temp(testCase, idx, ele_temp): if ii == "NBANDS": continue testCase.assertAlmostEqual( - incar0[ii], incar1[ii], msg="key %s differ" % (ii), places=5 + incar0[ii], incar1[ii], msg=f"key {ii} differ", places=5 ) os.chdir(cwd)