diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e7250132..f4c648e7 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -19,7 +19,7 @@ repos: # Python - repo: https://github.com/astral-sh/ruff-pre-commit # Ruff version. - rev: v0.4.1 + rev: v0.4.2 hooks: - id: ruff args: ["--fix"] diff --git a/docs/make_format.py b/docs/make_format.py index 4e78ce53..8a7878f9 100644 --- a/docs/make_format.py +++ b/docs/make_format.py @@ -134,13 +134,13 @@ def generate_sub_format_pages(formats: dict): for format, alias in formats.items(): # format: Format, alias: list[str] buff = [] - buff.append(".. _%s:" % format.__name__) + buff.append(f".. _{format.__name__}:") buff.append("") for aa in alias: - buff.append("%s format" % aa) + buff.append(f"{aa} format") buff.append("=" * len(buff[-1])) buff.append("") - buff.append("Class: %s" % get_cls_link(format)) + buff.append(f"Class: {get_cls_link(format)}") buff.append("") docstring = format.__doc__ @@ -158,10 +158,10 @@ def generate_sub_format_pages(formats: dict): buff.append(f".. _{format.__name__}_{method}:") buff.append("") if method.startswith("from_"): - buff.append("Convert from this format to %s" % method_classes[method]) + buff.append(f"Convert from this format to {method_classes[method]}") buff.append("`" * len(buff[-1])) elif method.startswith("to_"): - buff.append("Convert from %s to this format" % method_classes[method]) + buff.append(f"Convert from {method_classes[method]} to this format") buff.append("`" * len(buff[-1])) buff.append("") method_obj = getattr(format, method) @@ -224,10 +224,7 @@ def generate_sub_format_pages(formats: dict): buff.append(""" :noindex:""") buff.append("") if docstring is None or method not in format.__dict__: - docstring = ( - """ Convert this format to :class:`%s`.""" - % (method_classes[method]) - ) + docstring = f""" Convert this format to :class:`{method_classes[method]}`.""" doc_obj = SphinxDocString(docstring) if len(doc_obj["Parameters"]) > 0: doc_obj["Parameters"] = [ @@ -295,7 +292,7 @@ def generate_sub_format_pages(formats: dict): ) ): docstring = ( - "Convert :class:`%s` to this format." % (method_classes[method]) + f"Convert :class:`{method_classes[method]}` to this format." ) doc_obj = SphinxDocString(docstring) if len(doc_obj["Parameters"]) > 0: @@ -324,7 +321,7 @@ def generate_sub_format_pages(formats: dict): buff.append("") buff.append("") - with open("formats/%s.rst" % format.__name__, "w") as rstfile: + with open(f"formats/{format.__name__}.rst", "w") as rstfile: rstfile.write("\n".join(buff)) @@ -342,8 +339,8 @@ def generate_sub_format_pages(formats: dict): for kk, vv in formats.items(): writer.writerow( { - "Format": ":ref:`%s`" % kk.__name__, - "Alias": "\n".join("``%s``" % vvv for vvv in vv), + "Format": f":ref:`{kk.__name__}`", + "Alias": "\n".join(f"``{vvv}``" for vvv in vv), "Supported Conversions": "\n".join( method_links[mtd].format(kk.__name__, mtd) for mtd in check_supported(kk) @@ -364,7 +361,7 @@ def generate_sub_format_pages(formats: dict): writer.writerow( { "Class": get_cls_link(kk), - "Alias": "\n".join("``%s``" % vvv for vvv in vv), + "Alias": "\n".join(f"``{vvv}``" for vvv in vv), } ) @@ -381,7 +378,7 @@ def generate_sub_format_pages(formats: dict): writer.writerow( { "Class": get_cls_link(kk), - "Alias": "\n".join("``%s``" % vvv for vvv in vv), + "Alias": "\n".join(f"``{vvv}``" for vvv in vv), } ) generate_sub_format_pages(formats) diff --git a/dpdata/abacus/md.py b/dpdata/abacus/md.py index 4b8ec038..b96a0fd0 100644 --- a/dpdata/abacus/md.py +++ b/dpdata/abacus/md.py @@ -28,7 +28,7 @@ def get_path_out(fname, inlines): for line in inlines: if len(line) > 0 and "suffix" in line and "suffix" == line.split()[0]: suffix = line.split()[1] - path_out = os.path.join(fname, "OUT.%s/" % suffix) + path_out = os.path.join(fname, f"OUT.{suffix}/") break return path_out @@ -189,7 +189,7 @@ def get_frame(fname): unconv_stru += "%d " % i ndump = len(energy) if unconv_stru != "": - warnings.warn("Structure %s are unconverged and not collected!" % unconv_stru) + warnings.warn(f"Structure {unconv_stru} are unconverged and not collected!") for iframe in range(ndump): stress[iframe] *= np.linalg.det(cells[iframe, :, :].reshape([3, 3])) diff --git a/dpdata/abacus/relax.py b/dpdata/abacus/relax.py index 346120c4..fb3c8da0 100644 --- a/dpdata/abacus/relax.py +++ b/dpdata/abacus/relax.py @@ -183,7 +183,7 @@ def get_frame(fname): ) logf = get_log_file(fname, inlines) - assert os.path.isfile(logf), "Error: can not find %s" % logf + assert os.path.isfile(logf), f"Error: can not find {logf}" with open(logf) as f1: lines = f1.readlines() diff --git a/dpdata/abacus/scf.py b/dpdata/abacus/scf.py index 966410d6..df50b010 100644 --- a/dpdata/abacus/scf.py +++ b/dpdata/abacus/scf.py @@ -23,7 +23,7 @@ def CheckFile(ifile): if not os.path.isfile(ifile): - print("Can not find file %s" % ifile) + print(f"Can not find file {ifile}") return False return True @@ -91,7 +91,7 @@ def get_path_out(fname, inlines): for line in inlines: if "suffix" in line and "suffix" == line.split()[0]: suffix = line.split()[1] - path_out = os.path.join(fname, "OUT.%s/running_scf.log" % suffix) + path_out = os.path.join(fname, f"OUT.{suffix}/running_scf.log") break return path_out @@ -131,7 +131,7 @@ def get_coords(celldm, cell, geometry_inlines, inlines=None): tmp = np.matmul(xyz, cell) xyz = tmp else: - print("coord_type = %s" % coord_type) + print(f"coord_type = {coord_type}") raise RuntimeError( "Input coordination type is invalid.\n Only direct and cartesian are accepted." ) @@ -367,11 +367,11 @@ def make_unlabeled_stru( for iele in range(len(data["atom_names"])): out += data["atom_names"][iele] + " " if mass is not None: - out += "%.3f " % mass[iele] + out += f"{mass[iele]:.3f} " else: out += "1 " if pp_file is not None: - out += "%s\n" % pp_file[iele] + out += f"{pp_file[iele]}\n" else: out += "\n" out += "\n" @@ -380,12 +380,12 @@ def make_unlabeled_stru( assert len(numerical_orbital) == len(data["atom_names"]) out += "NUMERICAL_ORBITAL\n" for iele in range(len(numerical_orbital)): - out += "%s\n" % numerical_orbital[iele] + out += f"{numerical_orbital[iele]}\n" out += "\n" if numerical_descriptor is not None: assert isinstance(numerical_descriptor, str) - out += "NUMERICAL_DESCRIPTOR\n%s\n" % numerical_descriptor + out += f"NUMERICAL_DESCRIPTOR\n{numerical_descriptor}\n" out += "\n" out += "LATTICE_CONSTANT\n" diff --git a/dpdata/cli.py b/dpdata/cli.py index 07e7b4b5..2e39d17d 100644 --- a/dpdata/cli.py +++ b/dpdata/cli.py @@ -37,9 +37,7 @@ def dpdata_parser() -> argparse.ArgumentParser: ) parser.add_argument("--type-map", "-t", type=str, nargs="+", help="type map") - parser.add_argument( - "--version", action="version", version="dpdata v%s" % __version__ - ) + parser.add_argument("--version", action="version", version=f"dpdata v{__version__}") return parser diff --git a/dpdata/data_type.py b/dpdata/data_type.py index b5141a4e..64d4c5b1 100644 --- a/dpdata/data_type.py +++ b/dpdata/data_type.py @@ -121,7 +121,7 @@ def check(self, system: "System"): else: raise RuntimeError("Unsupported type to check shape") elif self.required: - raise DataError("%s not found in data" % self.name) + raise DataError(f"{self.name} not found in data") __system_data_type_plugin = Plugin() diff --git a/dpdata/deepmd/hdf5.py b/dpdata/deepmd/hdf5.py index ef54d862..992a1344 100644 --- a/dpdata/deepmd/hdf5.py +++ b/dpdata/deepmd/hdf5.py @@ -139,7 +139,7 @@ def to_system_data( for ii in sets: set = g[ii] - fn = "%s.npy" % prop["fn"] + fn = "{}.npy".format(prop["fn"]) if fn in set.keys(): dd = set[fn][:] nframes = dd.shape[0] @@ -257,7 +257,7 @@ def dump( for dt, prop in data_types.items(): if dt in reshaped_data: set_folder.create_dataset( - "%s.npy" % prop["fn"], data=reshaped_data[dt][set_stt:set_end] + "{}.npy".format(prop["fn"]), data=reshaped_data[dt][set_stt:set_end] ) if nopbc: diff --git a/dpdata/format.py b/dpdata/format.py index c231ef72..cd77561a 100644 --- a/dpdata/format.py +++ b/dpdata/format.py @@ -184,7 +184,7 @@ def from_system(self, file_name, **kwargs): system data, whose keys are defined in System.DTYPES """ raise NotImplementedError( - "%s doesn't support System.from" % (self.__class__.__name__) + f"{self.__class__.__name__} doesn't support System.from" ) def to_system(self, data, *args, **kwargs): @@ -200,7 +200,7 @@ def to_system(self, data, *args, **kwargs): keyword arguments that will be passed from the method """ raise NotImplementedError( - "%s doesn't support System.to" % (self.__class__.__name__) + f"{self.__class__.__name__} doesn't support System.to" ) def from_labeled_system(self, file_name, **kwargs): @@ -219,7 +219,7 @@ def from_labeled_system(self, file_name, **kwargs): system data, whose keys are defined in LabeledSystem.DTYPES """ raise NotImplementedError( - "%s doesn't support LabeledSystem.from" % (self.__class__.__name__) + f"{self.__class__.__name__} doesn't support LabeledSystem.from" ) def to_labeled_system(self, data, *args, **kwargs): @@ -254,7 +254,7 @@ def from_bond_order_system(self, file_name, **kwargs): system data """ raise NotImplementedError( - "%s doesn't support BondOrderSystem.from" % (self.__class__.__name__) + f"{self.__class__.__name__} doesn't support BondOrderSystem.from" ) def to_bond_order_system(self, data, rdkit_mol, *args, **kwargs): @@ -313,7 +313,7 @@ def from_multi_systems(self, directory, **kwargs): if os.path.isdir(os.path.join(directory, name)) ] raise NotImplementedError( - "%s doesn't support MultiSystems.from" % (self.__class__.__name__) + f"{self.__class__.__name__} doesn't support MultiSystems.from" ) def to_multi_systems(self, formulas, directory, **kwargs): @@ -333,7 +333,7 @@ def to_multi_systems(self, formulas, directory, **kwargs): if self.MultiMode == self.MultiModes.Directory: return [os.path.join(directory, ff) for ff in formulas] raise NotImplementedError( - "%s doesn't support MultiSystems.to" % (self.__class__.__name__) + f"{self.__class__.__name__} doesn't support MultiSystems.to" ) def mix_system(self, *system, type_map, **kwargs): @@ -354,5 +354,5 @@ def mix_system(self, *system, type_map, **kwargs): dict of mixed system with key 'atom_numbs' """ raise NotImplementedError( - "%s doesn't support System.from" % (self.__class__.__name__) + f"{self.__class__.__name__} doesn't support System.from" ) diff --git a/dpdata/periodic_table.py b/dpdata/periodic_table.py index e6f16bc9..47179320 100644 --- a/dpdata/periodic_table.py +++ b/dpdata/periodic_table.py @@ -114,7 +114,7 @@ class Element: def __init__(self, symbol: str): assert symbol in ELEMENTS - self.symbol = "%s" % symbol + self.symbol = f"{symbol}" d = _pdt[symbol] self._Z = d["atomic_no"] self._name = d["name"] @@ -127,7 +127,7 @@ def __str__(self): return self.symbol def __repr__(self): - return "Element : %s" % self.symbol + return f"Element : {self.symbol}" @classmethod def from_Z(cls, Z): diff --git a/dpdata/pwmat/atomconfig.py b/dpdata/pwmat/atomconfig.py index 28cfaebc..f128aa5f 100644 --- a/dpdata/pwmat/atomconfig.py +++ b/dpdata/pwmat/atomconfig.py @@ -58,7 +58,7 @@ def from_system_data(system, f_idx=0, skip_zeros=True): ret += "\n" for ii in system["cells"][f_idx]: for jj in ii: - ret += "%.16e " % jj + ret += f"{jj:.16e} " ret += "\n" ret += "POSITION" ret += "\n" diff --git a/dpdata/stat.py b/dpdata/stat.py index 1f6193af..8de64982 100644 --- a/dpdata/stat.py +++ b/dpdata/stat.py @@ -52,12 +52,12 @@ class ErrorsBase(metaclass=ABCMeta): SYSTEM_TYPE = object def __init__(self, system_1: SYSTEM_TYPE, system_2: SYSTEM_TYPE) -> None: - assert isinstance(system_1, self.SYSTEM_TYPE), ( - "system_1 should be %s" % self.SYSTEM_TYPE.__name__ - ) - assert isinstance(system_2, self.SYSTEM_TYPE), ( - "system_2 should be %s" % self.SYSTEM_TYPE.__name__ - ) + assert isinstance( + system_1, self.SYSTEM_TYPE + ), f"system_1 should be {self.SYSTEM_TYPE.__name__}" + assert isinstance( + system_2, self.SYSTEM_TYPE + ), f"system_2 should be {self.SYSTEM_TYPE.__name__}" self.system_1 = system_1 self.system_2 = system_2 diff --git a/dpdata/system.py b/dpdata/system.py index fd635257..a848066e 100644 --- a/dpdata/system.py +++ b/dpdata/system.py @@ -450,9 +450,9 @@ def append(self, system): # check if the first shape is nframes if tt.shape is not None and Axis.NFRAMES in tt.shape: if tt.name not in self.data and tt.name in system.data: - raise RuntimeError("system has %s, but this does not" % tt.name) + raise RuntimeError(f"system has {tt.name}, but this does not") elif tt.name in self.data and tt.name not in system.data: - raise RuntimeError("this has %s, but system does not" % tt.name) + raise RuntimeError(f"this has {tt.name}, but system does not") elif tt.name not in self.data and tt.name not in system.data: # skip if both not exist continue @@ -1142,7 +1142,7 @@ def __str__(self): ret += "\nFrame Numbers : %d" % self.get_nframes() ret += "\nAtom Numbers : %d" % self.get_natoms() status = "Yes" if self.has_virial() else "No" - ret += "\nIncluding Virials : %s" % status + ret += f"\nIncluding Virials : {status}" ret += "\nElement List :" ret += "\n-------------------" ret += "\n" + " ".join(map(str, self.get_atom_names())) @@ -1645,9 +1645,7 @@ def get_func(ff): def from_format(self, file_name, **kwargs): return self.from_fmt_obj(ff(), file_name, **kwargs) - from_format.__doc__ = "Read data from :class:`%s` format." % ( - get_cls_name(ff) - ) + from_format.__doc__ = f"Read data from :class:`{get_cls_name(ff)}` format." return from_format setattr(System, method, get_func(formatcls)) @@ -1660,7 +1658,7 @@ def get_func(ff): def to_format(self, *args, **kwargs): return self.to_fmt_obj(ff(), *args, **kwargs) - to_format.__doc__ = "Dump data to :class:`%s` format." % (get_cls_name(ff)) + to_format.__doc__ = f"Dump data to :class:`{get_cls_name(ff)}` format." return to_format setattr(System, method, get_func(formatcls)) diff --git a/dpdata/vasp/poscar.py b/dpdata/vasp/poscar.py index 95f9c15e..fde0f8fb 100644 --- a/dpdata/vasp/poscar.py +++ b/dpdata/vasp/poscar.py @@ -59,12 +59,12 @@ def from_system_data(system, f_idx=0, skip_zeros=True): ret += "1.0\n" for ii in system["cells"][f_idx]: for jj in ii: - ret += "%.16e " % jj + ret += f"{jj:.16e} " ret += "\n" for idx, ii in enumerate(system["atom_names"]): if system["atom_numbs"][idx] == 0: continue - ret += "%s " % ii + ret += f"{ii} " ret += "\n" for ii in system["atom_numbs"]: if ii == 0: