Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[pre-commit.ci] pre-commit autoupdate #648

Merged
merged 2 commits into from
May 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down
27 changes: 12 additions & 15 deletions docs/make_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__
Expand All @@ -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)
Expand Down Expand Up @@ -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"] = [
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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))


Expand All @@ -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)
Expand All @@ -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),
}
)

Expand All @@ -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)
4 changes: 2 additions & 2 deletions dpdata/abacus/md.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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]))
Expand Down
2 changes: 1 addition & 1 deletion dpdata/abacus/relax.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
14 changes: 7 additions & 7 deletions dpdata/abacus/scf.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")

Check warning on line 26 in dpdata/abacus/scf.py

View check run for this annotation

Codecov / codecov/patch

dpdata/abacus/scf.py#L26

Added line #L26 was not covered by tests
return False
return True

Expand Down Expand Up @@ -91,7 +91,7 @@
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

Expand Down Expand Up @@ -131,7 +131,7 @@
tmp = np.matmul(xyz, cell)
xyz = tmp
else:
print("coord_type = %s" % coord_type)
print(f"coord_type = {coord_type}")

Check warning on line 134 in dpdata/abacus/scf.py

View check run for this annotation

Codecov / codecov/patch

dpdata/abacus/scf.py#L134

Added line #L134 was not covered by tests
raise RuntimeError(
"Input coordination type is invalid.\n Only direct and cartesian are accepted."
)
Expand Down Expand Up @@ -367,11 +367,11 @@
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"
Expand All @@ -380,12 +380,12 @@
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"
Expand Down
4 changes: 1 addition & 3 deletions dpdata/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,7 @@
)
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__}")

Check warning on line 40 in dpdata/cli.py

View check run for this annotation

Codecov / codecov/patch

dpdata/cli.py#L40

Added line #L40 was not covered by tests
return parser


Expand Down
2 changes: 1 addition & 1 deletion dpdata/data_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@
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")

Check warning on line 124 in dpdata/data_type.py

View check run for this annotation

Codecov / codecov/patch

dpdata/data_type.py#L124

Added line #L124 was not covered by tests


__system_data_type_plugin = Plugin()
Expand Down
4 changes: 2 additions & 2 deletions dpdata/deepmd/hdf5.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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:
Expand Down
14 changes: 7 additions & 7 deletions dpdata/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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):
Expand All @@ -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):
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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):
Expand All @@ -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):
Expand All @@ -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"
)
4 changes: 2 additions & 2 deletions dpdata/periodic_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand All @@ -127,7 +127,7 @@
return self.symbol

def __repr__(self):
return "Element : %s" % self.symbol
return f"Element : {self.symbol}"

Check warning on line 130 in dpdata/periodic_table.py

View check run for this annotation

Codecov / codecov/patch

dpdata/periodic_table.py#L130

Added line #L130 was not covered by tests

@classmethod
def from_Z(cls, Z):
Expand Down
2 changes: 1 addition & 1 deletion dpdata/pwmat/atomconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
12 changes: 6 additions & 6 deletions dpdata/stat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
12 changes: 5 additions & 7 deletions dpdata/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -450,9 +450,9 @@
# 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")

Check warning on line 453 in dpdata/system.py

View check run for this annotation

Codecov / codecov/patch

dpdata/system.py#L453

Added line #L453 was not covered by tests
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")

Check warning on line 455 in dpdata/system.py

View check run for this annotation

Codecov / codecov/patch

dpdata/system.py#L455

Added line #L455 was not covered by tests
elif tt.name not in self.data and tt.name not in system.data:
# skip if both not exist
continue
Expand Down Expand Up @@ -1142,7 +1142,7 @@
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}"

Check warning on line 1145 in dpdata/system.py

View check run for this annotation

Codecov / codecov/patch

dpdata/system.py#L1145

Added line #L1145 was not covered by tests
ret += "\nElement List :"
ret += "\n-------------------"
ret += "\n" + " ".join(map(str, self.get_atom_names()))
Expand Down Expand Up @@ -1645,9 +1645,7 @@
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))
Expand All @@ -1660,7 +1658,7 @@
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))
Expand Down
4 changes: 2 additions & 2 deletions dpdata/vasp/poscar.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down