Skip to content

Commit

Permalink
REformat using latest ruff.
Browse files Browse the repository at this point in the history
  • Loading branch information
shyuep committed Jan 9, 2025
1 parent 1d013f3 commit fb1ca91
Show file tree
Hide file tree
Showing 46 changed files with 153 additions and 176 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ def get_structure(self, morphing_factor):

for morphing in self.morphing_description:
if morphing["site_type"] != "neighbor":
raise ValueError(f"Key \"site_type\" is {morphing['site_type']} while it can only be neighbor")
raise ValueError(f'Key "site_type" is {morphing["site_type"]} while it can only be neighbor')

site_idx = morphing["ineighbor"] + 1
if morphing["expansion_origin"] == "central_site":
Expand Down
3 changes: 1 addition & 2 deletions dev_scripts/chemenv/view_environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,7 @@
vis = None
while True:
cg_symbol = input(
'Enter symbol of the geometry you want to see, "l" to see the list '
'of existing geometries or "q" to quit : '
'Enter symbol of the geometry you want to see, "l" to see the list of existing geometries or "q" to quit : '
)
if cg_symbol == "q":
break
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -714,8 +714,7 @@ def elastic_centered_graph(self, start_node=None):
nbunch=[node_neighbor], data=True, keys=True
)
logging.debug(
f" Delta image from {node=} to {node_neighbor=} : "
f"({', '.join(map(str, d_delta))})"
f" Delta image from {node=} to {node_neighbor=} : ({', '.join(map(str, d_delta))})"
)
# Loop on the edges of this neighbor
for n1, n2, key, edata in node_neighbor_edges:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,8 +189,7 @@ def __str__(self):
)
else:
outs.append(
"Points are referenced to the centroid (calculated without the central site)"
f" :\n {self.centre}\n"
f"Points are referenced to the centroid (calculated without the central site) :\n {self.centre}\n"
)
return "\n".join(outs)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -854,7 +854,7 @@ def dp_func(dp):
return dp

else:
raise ValueError(f"Wrong value for distance parameter plot type \"{plot_type['distance_parameter'][0]}\"")
raise ValueError(f'Wrong value for distance parameter plot type "{plot_type["distance_parameter"][0]}"')

if plot_type["angle_parameter"][0] == "one_minus_gamma":
ylabel = "Angle parameter : $1.0-\\gamma$"
Expand All @@ -872,7 +872,7 @@ def ap_func(ap):
return ap

else:
raise ValueError(f"Wrong value for angle parameter plot type \"{plot_type['angle_parameter'][0]}\"")
raise ValueError(f'Wrong value for angle parameter plot type "{plot_type["angle_parameter"][0]}"')
dist_limits = [dp_func(dp) for dp in dist_limits]
ang_limits = [ap_func(ap) for ap in ang_limits]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -463,7 +463,7 @@ def neighbors_surfaces_bounded(self, isite, surface_calculation_options=None):
}
else:
raise ValueError(
f'Type {surface_calculation_options["type"]!r} for the surface calculation in DetailedVoronoiContainer '
f"Type {surface_calculation_options['type']!r} for the surface calculation in DetailedVoronoiContainer "
"is invalid"
)
max_dist = surface_calculation_options["distance_bounds"]["upper"] + 0.1
Expand Down
2 changes: 1 addition & 1 deletion src/pymatgen/analysis/chemenv/utils/chemenv_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def package_options_description(self):
"""Describe package options."""
out = "Package options :\n"
out += f" - Maximum distance factor : {self.package_options['default_max_distance_factor']:.4f}\n"
out += f" - Default strategy is \"{self.package_options['default_strategy']['strategy']}\" :\n"
out += f' - Default strategy is "{self.package_options["default_strategy"]["strategy"]}" :\n'
strategy_class = strategies_class_lookup[self.package_options["default_strategy"]["strategy"]]
out += f"{strategy_class.STRATEGY_DESCRIPTION}\n"
out += " with options :\n"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def get_lower_and_upper_f(surface_calculation_options):
lower_points=lower_points, upper_points=upper_points, degree=degree
)
else:
raise ValueError(f"Surface calculation of type \"{surface_calculation_options['type']}\" is not implemented")
raise ValueError(f'Surface calculation of type "{surface_calculation_options["type"]}" is not implemented')
return lower_and_upper_functions


Expand Down
5 changes: 1 addition & 4 deletions src/pymatgen/analysis/chemenv/utils/graph_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,10 +120,7 @@ def _c2index_isreverse(c1, c2):
elif c2_1_index == c2_0_index - 1:
reverse = True
else:
msg = (
"Second node of cycle c1 in cycle c2 is not just after or "
"just before first node of cycle c1 in cycle c2."
)
msg = "Second node of cycle c1 in cycle c2 is not just after or just before first node of cycle c1 in cycle c2."
return None, None, msg
return c2_0_index, reverse, ""

Expand Down
5 changes: 1 addition & 4 deletions src/pymatgen/analysis/chemenv/utils/scripts_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,10 +293,7 @@ def compute_environments(chemenv_configuration):
if ce is None:
continue
the_cg = all_cg.get_geometry_from_mp_symbol(ce[0])
msg = (
f"Environment for site #{site_idx} {reduced_formula}"
f" ({comp}) : {the_cg.name} ({ce[0]})\n"
)
msg = f"Environment for site #{site_idx} {reduced_formula} ({comp}) : {the_cg.name} ({ce[0]})\n"
else:
msg = f"Environments for site #{site_idx} {reduced_formula} ({comp}) : \n"
for ce in ces:
Expand Down
6 changes: 2 additions & 4 deletions src/pymatgen/analysis/graphs.py
Original file line number Diff line number Diff line change
Expand Up @@ -631,8 +631,7 @@ def break_edge(
self.graph.remove_edge(to_index, from_index, edge_index)
else:
raise ValueError(
f"Edge cannot be broken between {from_index} and {to_index}; "
f"no edge exists between those sites."
f"Edge cannot be broken between {from_index} and {to_index}; no edge exists between those sites."
)

def remove_nodes(self, indices: Sequence[int | None]) -> None:
Expand Down Expand Up @@ -1976,8 +1975,7 @@ def break_edge(self, from_index, to_index, allow_reverse=False):
self.graph.remove_edge(to_index, from_index)
else:
raise ValueError(
f"Edge cannot be broken between {from_index} and {to_index}; "
f"no edge exists between those sites."
f"Edge cannot be broken between {from_index} and {to_index}; no edge exists between those sites."
)

def remove_nodes(self, indices: list[int]) -> None:
Expand Down
3 changes: 1 addition & 2 deletions src/pymatgen/analysis/interface_reactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,7 @@ def __init__(

if isinstance(pd, GrandPotentialPhaseDiagram) and not bypass_grand_warning:
raise TypeError(
"Please use the GrandPotentialInterfacialReactivity "
"class for interfacial reactions with open elements!"
"Please use the GrandPotentialInterfacialReactivity class for interfacial reactions with open elements!"
)

self.c1 = c1
Expand Down
3 changes: 1 addition & 2 deletions src/pymatgen/analysis/magnetism/heisenberg.py
Original file line number Diff line number Diff line change
Expand Up @@ -523,8 +523,7 @@ def get_mft_temperature(self, j_avg):

if mft_t > 1500: # Not sensible!
logging.warning(
"This mean field estimate is too high! Probably "
"the true low energy orderings were not given as inputs."
"This mean field estimate is too high! Probably the true low energy orderings were not given as inputs."
)

return mft_t
Expand Down
3 changes: 1 addition & 2 deletions src/pymatgen/analysis/pourbaix_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,7 @@ def __repr__(self) -> str:
self.entry_id,
)
return (
f"{type(self).__name__}({self.entry.composition} with {energy=:.4f}, {npH=}, "
f"{nPhi=}, {nH2O=}, {entry_id=})"
f"{type(self).__name__}({self.entry.composition} with {energy=:.4f}, {npH=}, {nPhi=}, {nH2O=}, {entry_id=})"
)

@property
Expand Down
3 changes: 1 addition & 2 deletions src/pymatgen/analysis/thermochemistry.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,5 @@ def __repr__(self):

def __str__(self):
return (
f"{self.type}_{self.formula}_{self.phaseinfo} = {self.value}, Valid T : {self.temp_range}, "
f"Ref = {self.ref}"
f"{self.type}_{self.formula}_{self.phaseinfo} = {self.value}, Valid T : {self.temp_range}, Ref = {self.ref}"
)
2 changes: 1 addition & 1 deletion src/pymatgen/command_line/critic2_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -701,7 +701,7 @@ def _remap_indices(self):
if len(node_mapping) != len(self.structure):
warnings.warn(
f"Check that all sites in input structure ({len(self.structure)}) have "
f"been detected by critic2 ({ len(node_mapping)}).",
f"been detected by critic2 ({len(node_mapping)}).",
stacklevel=2,
)

Expand Down
4 changes: 2 additions & 2 deletions src/pymatgen/core/composition.py
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ def formula(self) -> str:
"""
sym_amt = self.get_el_amt_dict()
syms = sorted(sym_amt, key=lambda sym: get_el_sp(sym).X)
formula = [f"{s}{formula_double_format(sym_amt[s], ignore_ones= False)}" for s in syms]
formula = [f"{s}{formula_double_format(sym_amt[s], ignore_ones=False)}" for s in syms]
return " ".join(formula)

@property
Expand All @@ -386,7 +386,7 @@ def iupac_formula(self) -> str:
"""
sym_amt = self.get_el_amt_dict()
syms = sorted(sym_amt, key=lambda s: get_el_sp(s).iupac_ordering)
formula = [f"{s}{formula_double_format(sym_amt[s], ignore_ones= False)}" for s in syms]
formula = [f"{s}{formula_double_format(sym_amt[s], ignore_ones=False)}" for s in syms]
return " ".join(formula)

@property
Expand Down
4 changes: 2 additions & 2 deletions src/pymatgen/core/trajectory.py
Original file line number Diff line number Diff line change
Expand Up @@ -455,14 +455,14 @@ def write_Xdatcar(
_lattice = self.lattice if self.constant_lattice else self.lattice[idx]

for latt_vec in _lattice:
lines.append(f'{" ".join(map(str, latt_vec))}')
lines.append(f"{' '.join(map(str, latt_vec))}")

lines.extend((" ".join(site_symbols), " ".join(map(str, n_atoms))))

lines.append(f"Direct configuration= {idx + 1}")

for coord, specie in zip(coords, self.species, strict=True):
line = f'{" ".join(format_str.format(c) for c in coord)} {specie}'
line = f"{' '.join(format_str.format(c) for c in coord)} {specie}"
lines.append(line)

xdatcar_str = "\n".join(lines) + "\n"
Expand Down
2 changes: 1 addition & 1 deletion src/pymatgen/ext/optimade.py
Original file line number Diff line number Diff line change
Expand Up @@ -473,7 +473,7 @@ def _get_comp(sp_dict):
exceptions.add(str(exc))

if exceptions:
_logger.error(f'Failed to parse returned data for {url}: {", ".join(exceptions)}')
_logger.error(f"Failed to parse returned data for {url}: {', '.join(exceptions)}")

return snls

Expand Down
2 changes: 1 addition & 1 deletion src/pymatgen/io/abinit/variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ def format_list2d(values, float_decimal=0):
line = "\n"
for lst in values:
for val in lst:
line += f" {val:{{fmt_spec}}}"
line += f" {val:{ {fmt_spec} }}"
line += "\n"

return line.rstrip("\n")
Expand Down
4 changes: 2 additions & 2 deletions src/pymatgen/io/aims/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,11 +198,11 @@ def get_header(self, filename: str) -> str:
"""
return textwrap.dedent(
f"""\
#{'=' * 72}
#{"=" * 72}
# FHI-aims geometry file: {filename}
# File generated from pymatgen
# {time.asctime()}
#{'=' * 72}
#{"=" * 72}
"""
)

Expand Down
5 changes: 1 addition & 4 deletions src/pymatgen/io/aims/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1067,10 +1067,7 @@ def get_aims_out_chunks(content: str | TextIOWrapper, header_chunk: AimsOutHeade
# don't end chunk on next Re-initialization
patterns = [
("Self-consistency cycle not yet converged - restarting mixer to attempt better convergence."),
(
"Components of the stress tensor (for mathematical "
"background see comments in numerical_stress.f90)."
),
("Components of the stress tensor (for mathematical background see comments in numerical_stress.f90)."),
"Calculation of numerical stress completed",
]
if any(pattern in line for pattern in patterns):
Expand Down
4 changes: 1 addition & 3 deletions src/pymatgen/io/vasp/outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -693,9 +693,7 @@ def final_energy(self) -> float:

except (IndexError, KeyError):
warnings.warn(
"Calculation does not have a total energy. "
"Possibly a GW or similar kind of run. "
"Infinity is returned.",
"Calculation does not have a total energy. Possibly a GW or similar kind of run. Infinity is returned.",
stacklevel=2,
)
return float("inf")
Expand Down
2 changes: 1 addition & 1 deletion src/pymatgen/io/xr.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def __str__(self):
# There are actually 10 more fields per site
# in a typical xr file from GULP, for example.
for idx, site in enumerate(self.structure, start=1):
output.append(f"{idx } {site.specie} {site.x:.4f} {site.y:.4f} {site.z:.4f}")
output.append(f"{idx} {site.specie} {site.x:.4f} {site.y:.4f} {site.z:.4f}")
mat = self.structure.lattice.matrix
for _ in range(2):
for j in range(3):
Expand Down
3 changes: 1 addition & 2 deletions src/pymatgen/phonon/thermal_displacements.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,8 +272,7 @@ def compute_directionality_quality_criterion(
for spec1, spec2 in zip(self.structure.species, other.structure.species, strict=True):
if spec1 != spec2:
raise ValueError(
"Species in both structures are not the same! "
"Please use structures that are similar to each other"
"Species in both structures are not the same! Please use structures that are similar to each other"
)
# check if structures match
structure_match = StructureMatcher()
Expand Down
3 changes: 1 addition & 2 deletions src/pymatgen/transformations/advanced_transformations.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,8 +205,7 @@ def apply_transformation(self, structure: Structure, return_ranked_list: bool |
"""
if not return_ranked_list:
raise ValueError(
"MultipleSubstitutionTransformation has no single"
" best structure output. Must use return_ranked_list."
"MultipleSubstitutionTransformation has no single best structure output. Must use return_ranked_list."
)
outputs = []
for charge, el_list in self.substitution_dict.items():
Expand Down
2 changes: 1 addition & 1 deletion src/pymatgen/util/string.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ def charge_string(charge: float, brackets: bool = True, explicit_one: bool = Tru
explicit_one (bool): whether to include the number one for monovalent ions,
e.g. "+1" rather than "+". Default is True.
"""
chg_str = "(aq)" if charge == 0 else f"{formula_double_format(charge, ignore_ones= False):+}"
chg_str = "(aq)" if charge == 0 else f"{formula_double_format(charge, ignore_ones=False):+}"

if chg_str in ["+1", "-1"] and not explicit_one:
chg_str = chg_str.replace("1", "")
Expand Down
3 changes: 1 addition & 2 deletions src/pymatgen/vis/structure_vtk.py
Original file line number Diff line number Diff line change
Expand Up @@ -1216,8 +1216,7 @@ def keyPressEvent(self, obj, event):
parent.current_structure = parent.structures[parent.istruct]
parent.set_structure(parent.current_structure, reset_camera=False, to_unit_cell=False)
parent.display_info(
f"Animated movie : structure {istruct + 1}/{len(parent.structures)} "
f"(loop {iloop + 1}/{nloops})"
f"Animated movie : structure {istruct + 1}/{len(parent.structures)} (loop {iloop + 1}/{nloops})"
)
parent.ren_win.Render()
time.sleep(tloops)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -214,9 +214,9 @@ def test_perfect_environments(self):
max_cn=cg.coordination_number,
only_symbols=[mp_symbol],
)
assert (
abs(se.get_csm(0, mp_symbol)["symmetry_measure"] - 0.0) < 1e-8
), f"Failed to get perfect environment with {mp_symbol=}"
assert abs(se.get_csm(0, mp_symbol)["symmetry_measure"] - 0.0) < 1e-8, (
f"Failed to get perfect environment with {mp_symbol=}"
)

def test_disable_hints(self):
allcg = AllCoordinationGeometries()
Expand Down
Loading

0 comments on commit fb1ca91

Please sign in to comment.