Skip to content

Commit

Permalink
Unignore flake8 B028 and fix occurrences (#2807)
Browse files Browse the repository at this point in the history
* un-ignore flake8 B028 error and fix occurrences

* fix pymatgen/analysis/chemenv/coordination_environments/tests/test_coordination_geometries.py:299
  • Loading branch information
janosh committed Jan 18, 2023
1 parent e1c075c commit 582cb83
Show file tree
Hide file tree
Showing 27 changed files with 82 additions and 82 deletions.
21 changes: 14 additions & 7 deletions dev_scripts/chemenv/get_plane_permutations_optimized.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,15 @@ def prt2(string, printing_volume):


# Iterator function for the random permutations
def random_permutations_iterator(initial_permutation, npermutations):
for _ in range(npermutations):
def random_permutations_iterator(initial_permutation, n_permutations):
"""
It takes a list and returns an iterator that yields random permutations of that list
Args:
initial_permutation: the initial permutation of the data
n_permutations: the number of permutations to generate
"""
for _ in range(n_permutations):
shuffle(initial_permutation)
yield initial_permutation

Expand Down Expand Up @@ -157,7 +164,7 @@ def random_permutations_iterator(initial_permutation, npermutations):

cg = all_cg[cg_symbol]

print(f'Getting explicit permutations for geometry "{cg.name}" (symbol : "{cg_symbol}")\n')
print(f"Getting explicit permutations for geometry {cg.name!r} (symbol : {cg_symbol!r})\n")

# Setup of the local geometry finder
lgf = LocalGeometryFinder()
Expand Down Expand Up @@ -274,8 +281,8 @@ def random_permutations_iterator(initial_permutation, npermutations):

while True:
test = input(
f'Get the explicit optimized permutations for geometry "{cg.name}" (symbol : '
f'"{cg_symbol}") ? ("y" to confirm, "q" to quit)\n'
f"Get the explicit optimized permutations for geometry {cg.name!r} (symbol : "
f'{cg_symbol!r}) ? ("y" to confirm, "q" to quit)\n'
)
if test not in ["y", "q"]:
print("Wrong key, try again")
Expand All @@ -285,7 +292,7 @@ def random_permutations_iterator(initial_permutation, npermutations):
elif test == "q":
exit()
# 2. Optimization of the permutations
print(f'Getting explicit optimized permutations for geometry "{cg.name}" (symbol : "{cg_symbol}")\n')
print(f"Getting explicit optimized permutations for geometry {cg.name!r} (symbol : {cg_symbol!r})\n")
perms_used_algos = [dict() for algo in cg.algorithms]

# Loop on algorithms
Expand Down Expand Up @@ -424,7 +431,7 @@ def random_permutations_iterator(initial_permutation, npermutations):
algo.explicit_optimized_permutations = np.array(explicit_optimized_permutations)

test = input(
f'Save coordination geometry "{cg.name}" (symbol "{cg_symbol}") and new explicit and optimized '
f"Save coordination geometry {cg.name!r} (symbol {cg_symbol!r}) and new explicit and optimized "
'permutations ? ("y" to confirm)'
)
if test == "y":
Expand Down
2 changes: 1 addition & 1 deletion dev_scripts/chemenv/test_algos.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,4 @@
print(" => ", algos_results)
iperm += 1
t2 = time.clock()
print(f'Time to test {nperms} permutations for geometry "{cg.name}" (symbol "{cg_symbol}") : {t2 - t1:.2f} seconds')
print(f"Time to test {nperms} permutations for geometry {cg.name!r} (symbol {cg_symbol!r}) : {t2 - t1:.2f} seconds")
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ def __init__(
environments_data=None,
links_data=None,
graph=None,
):
) -> None:
"""
Constructor for the ConnectedComponent object.
Expand Down Expand Up @@ -354,7 +354,7 @@ def coordination_sequence(self, source_node, path_size=5, coordination="number",
elif coordination == "env:number":
cseq[0] = {source_node.coordination_environment: 1}
else:
raise ValueError(f'Coordination type "{coordination}" is not valid for coordination_sequence.')
raise ValueError(f"Coordination type {coordination!r} is not valid for coordination_sequence.")
while path_len < path_size:
new_ends = []
for current_node_end, current_delta_end in current_ends:
Expand All @@ -377,7 +377,7 @@ def coordination_sequence(self, source_node, path_size=5, coordination="number",
myenvs = [myend.coordination_environment for myend, _ in current_ends]
cseq[path_len] = {myenv: myenvs.count(myenv) for myenv in set(myenvs)}
else:
raise ValueError(f'Coordination type "{coordination}" is not valid for coordination_sequence.')
raise ValueError(f"Coordination type {coordination!r} is not valid for coordination_sequence.")
return cseq

def __len__(self):
Expand All @@ -395,7 +395,7 @@ def compute_periodicity(self, algorithm="all_simple_paths"):
elif algorithm == "cycle_basis":
self.compute_periodicity_cycle_basis()
else:
raise ValueError(f'Algorithm "{algorithm}" is not allowed to compute periodicity')
raise ValueError(f"Algorithm {algorithm!r} is not allowed to compute periodicity")
self._order_periodicity_vectors()

def compute_periodicity_all_simple_paths_algorithm(self):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,6 @@ def setup_parameters(self, multiple_environments_choice):
if multiple_environments_choice is not None:
if multiple_environments_choice not in ["TAKE_HIGHEST_FRACTION"]:
raise ValueError(
f'Option "{multiple_environments_choice}" for multiple_environments_choice is not allowed'
f"Option {multiple_environments_choice!r} for multiple_environments_choice is not allowed"
)
self.multiple_environments_choice = multiple_environments_choice
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ class AdditionalConditionInt(int, StrategyOption):

allowed_values = "Integer amongst :\n"
for integer, description in AdditionalConditions.CONDITION_DESCRIPTION.items():
allowed_values += f' - {integer:d} for "{description}"\n'
allowed_values += f" - {integer:d} for {description!r}\n"

def __new__(cls, integer):
"""Special int representing additional conditions."""
Expand Down Expand Up @@ -442,7 +442,7 @@ def __eq__(self, other: object) -> bool:
raise NotImplementedError()

def __str__(self):
out = f' Chemenv Strategy "{type(self).__name__}"\n'
out = f" Chemenv Strategy {type(self).__name__!r}\n"
out += f" {'=' * (19 + len(type(self).__name__))}\n\n"
out += f" Description :\n {'-' * 13}\n"
out += self.STRATEGY_DESCRIPTION
Expand Down Expand Up @@ -1335,7 +1335,7 @@ def __init__(self, average_type, aa, bb):
elif self.average_type == "arithmetic":
self.eval = self.aweight
else:
raise ValueError(f'Average type is "{average_type}" while it should be "geometric" or "arithmetic"')
raise ValueError(f"Average type is {average_type!r} while it should be 'geometric' or 'arithmetic'")
self.aa = aa
self.bb = bb
if self.aa == 0:
Expand Down Expand Up @@ -2046,7 +2046,7 @@ def __init__(
raise NotImplementedError()
# self.area_weight = self.w_area_has_intersection_smoothstep
else:
raise ValueError(f'Weight type is "{weight_type}" while it should be "has_intersection"')
raise ValueError(f'Weight type is {weight_type!r} while it should be "has_intersection"')
self.surface_definition = surface_definition
self.nb_sets_from_hints = nb_sets_from_hints
self.other_nb_sets = other_nb_sets
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ def __init__(self, hints_type, options):
neighbors set could be found from a "cap hint".
"""
if hints_type not in self.ALLOWED_HINTS_TYPES:
raise ValueError(f'Type "{type}" for NeighborsSetsHints is not allowed')
raise ValueError(f"Type {type!r} for NeighborsSetsHints is not allowed")
self.hints_type = hints_type
self.options = options

Expand Down Expand Up @@ -1171,7 +1171,7 @@ def get_geometry_from_name(self, name):
for gg in self.cg_list:
if gg.name == name or name in gg.alternative_names:
return gg
raise LookupError(f'No coordination geometry found with name "{name}"')
raise LookupError(f"No coordination geometry found with name {name!r}")

def get_geometry_from_IUPAC_symbol(self, IUPAC_symbol):
"""
Expand All @@ -1183,7 +1183,7 @@ def get_geometry_from_IUPAC_symbol(self, IUPAC_symbol):
for gg in self.cg_list:
if gg.IUPAC_symbol == IUPAC_symbol:
return gg
raise LookupError(f'No coordination geometry found with IUPAC symbol "{IUPAC_symbol}"')
raise LookupError(f"No coordination geometry found with IUPAC symbol {IUPAC_symbol!r}")

def get_geometry_from_IUCr_symbol(self, IUCr_symbol):
"""
Expand All @@ -1195,7 +1195,7 @@ def get_geometry_from_IUCr_symbol(self, IUCr_symbol):
for gg in self.cg_list:
if gg.IUCr_symbol == IUCr_symbol:
return gg
raise LookupError(f'No coordination geometry found with IUCr symbol "{IUCr_symbol}"')
raise LookupError(f"No coordination geometry found with IUCr symbol {IUCr_symbol!r}")

def get_geometry_from_mp_symbol(self, mp_symbol):
"""
Expand All @@ -1207,7 +1207,7 @@ def get_geometry_from_mp_symbol(self, mp_symbol):
for gg in self.cg_list:
if gg.mp_symbol == mp_symbol:
return gg
raise LookupError(f'No coordination geometry found with mp_symbol "{mp_symbol}"')
raise LookupError(f"No coordination geometry found with mp_symbol {mp_symbol!r}")

def is_a_valid_coordination_geometry(
self, mp_symbol=None, IUPAC_symbol=None, IUCr_symbol=None, name=None, cn=None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -785,7 +785,7 @@ def compute_structure_environments(
# Get possibly missing neighbors sets
if cg.neighbors_sets_hints is None:
continue
logging.debug(f' ... getting hints from cg with mp_symbol "{cg_symbol}" ...')
logging.debug(f" ... getting hints from cg with mp_symbol {cg_symbol!r} ...")
hints_info = {
"csm": cg_dict["symmetry_measure"],
"nb_set": nb_set,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -651,7 +651,7 @@ def get_csm(self, isite, mp_symbol):
raise ChemenvError(
"StructureEnvironments",
"get_csm",
f'Number of csms for site #{str(isite)} with mp_symbol "{mp_symbol}" = {str(len(csms))}',
f"Number of csms for site #{str(isite)} with mp_symbol {mp_symbol!r} = {str(len(csms))}",
)
return csms[0]

Expand Down Expand Up @@ -1968,7 +1968,7 @@ def site_has_clear_environment(self, isite, conditions=None):
if ce[target] > condition["maxnumber"]:
return False
else:
raise ValueError(f'Target "{target}" for condition of clear environment is not allowed')
raise ValueError(f"Target {target!r} for condition of clear environment is not allowed")
return True

def structure_has_clear_environments(self, conditions=None, skip_none=True, skip_empty=False):
Expand Down Expand Up @@ -2294,7 +2294,7 @@ def add_coord_geom(
raise ChemenvError(
self.__class__,
"add_coord_geom",
f'Coordination geometry with mp_symbol "{mp_symbol}" is not valid',
f"Coordination geometry with mp_symbol {mp_symbol!r} is not valid",
)
if mp_symbol in list(self.coord_geoms) and not override:
raise ChemenvError(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -296,21 +296,21 @@ def test_coordination_geometry(self):
assert allcg.get_geometry_from_name("Octahedron").mp_symbol == cg_oct.mp_symbol
with pytest.raises(LookupError) as exc_info:
allcg.get_geometry_from_name("Octahedran")
assert str(exc_info.value) == 'No coordination geometry found with name "Octahedran"'
assert str(exc_info.value) == "No coordination geometry found with name 'Octahedran'"

assert allcg.get_geometry_from_IUPAC_symbol("OC-6").mp_symbol == cg_oct.mp_symbol
with pytest.raises(LookupError) as exc_info:
allcg.get_geometry_from_IUPAC_symbol("OC-7")
assert str(exc_info.value) == 'No coordination geometry found with IUPAC symbol "OC-7"'
assert str(exc_info.value) == "No coordination geometry found with IUPAC symbol 'OC-7'"

assert allcg.get_geometry_from_IUCr_symbol("[6o]").mp_symbol == cg_oct.mp_symbol
with pytest.raises(LookupError) as exc_info:
allcg.get_geometry_from_IUCr_symbol("[6oct]")
assert str(exc_info.value) == 'No coordination geometry found with IUCr symbol "[6oct]"'
assert str(exc_info.value) == "No coordination geometry found with IUCr symbol '[6oct]'"

with pytest.raises(LookupError) as exc_info:
allcg.get_geometry_from_mp_symbol("O:7")
assert str(exc_info.value) == 'No coordination geometry found with mp_symbol "O:7"'
assert str(exc_info.value) == "No coordination geometry found with mp_symbol 'O:7'"

assert (
allcg.pretty_print(maxcn=4)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ def test_normalized_angle_distance_weight(self):
with pytest.raises(ValueError, match="Both exponents are 0."):
NormalizedAngleDistanceNbSetWeight(average_type="arithmetic", aa=0, bb=0)
with pytest.raises(
ValueError, match='Average type is "arithmetix" ' 'while it should be "geometric" or "arithmetic"'
ValueError, match="Average type is 'arithmetix' while it should be 'geometric' or 'arithmetic'"
):
NormalizedAngleDistanceNbSetWeight(average_type="arithmetix", aa=1, bb=1)

Expand Down
10 changes: 5 additions & 5 deletions pymatgen/analysis/chemenv/coordination_environments/voronoi.py
Original file line number Diff line number Diff line change
Expand Up @@ -475,7 +475,7 @@ def neighbors_surfaces_bounded(self, isite, surface_calculation_options=None):
}
else:
raise ValueError(
f'Type "{surface_calculation_options["type"]}" 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 Expand Up @@ -705,7 +705,7 @@ def voronoi_parameters_bounds_and_limits(self, isite, plot_type, max_dist):
dist_limits = [0.0, 1.0]
else:
raise NotImplementedError(
f"Plotting type \"{plot_type['distance_parameter']}\" for the distance is not implemented"
f"Plotting type {plot_type['distance_parameter']!r} for the distance is not implemented"
)
if plot_type["angle_parameter"][0] == "initial_normalized":
aa = [0.0]
Expand All @@ -718,7 +718,7 @@ def voronoi_parameters_bounds_and_limits(self, isite, plot_type, max_dist):
angle_bounds = np.array(aa)
else:
raise NotImplementedError(
f"Plotting type \"{plot_type['angle_parameter']}\" for the angle is not implemented"
f"Plotting type {plot_type['angle_parameter']!r} for the angle is not implemented"
)
ang_limits = [0.0, 1.0]
return {
Expand Down Expand Up @@ -854,7 +854,7 @@ def dp_func(dp):
for idist, dist in enumerate(mydists):
yy += mydcns[idist] * normal_cdf_step(xx, mean=dist, scale=scale)
else:
raise ValueError(f"Step function of type \"{step_function['type']}\" is not allowed")
raise ValueError(f"Step function of type {step_function['type']!r} is not allowed")
subplot.plot(xx, yy)

return fig
Expand Down Expand Up @@ -913,7 +913,7 @@ def ap_func(ap):
for iang, ang in enumerate(myangs):
yy += mydcns[iang] * normal_cdf_step(xx, mean=ang, scale=scale)
else:
raise ValueError(f"Step function of type \"{step_function['type']}\" is not allowed")
raise ValueError(f"Step function of type {step_function['type']!r} is not allowed")
subplot.plot(xx, yy)

return fig
Expand Down
6 changes: 3 additions & 3 deletions pymatgen/analysis/chemenv/utils/chemenv_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def setup(self):
print(" ... wrong key, try again ...")
print()
if test == "S":
print(f'Configuration has been saved to file "{config_file}"')
print(f"Configuration has been saved to file {config_file!r}")

@property
def has_materials_project_access(self):
Expand Down Expand Up @@ -117,7 +117,7 @@ def setup_package_options(self):
if len(strategy_class.STRATEGY_OPTIONS) > 0:
for option, option_dict in strategy_class.STRATEGY_OPTIONS.items():
while True:
print(f" => Enter value for option '{option}' (<ENTER> for default = {option_dict['default']})\n")
print(f" => Enter value for option {option!r} (<ENTER> for default = {option_dict['default']})\n")
print(" Valid options are :\n")
print(f" {option_dict['type'].allowed_values}")
test = input(" Your choice : ")
Expand Down Expand Up @@ -184,6 +184,6 @@ def auto_load(cls, root_dir=None):
return ChemEnvConfig(package_options=config_dict["package_options"])

except OSError:
print(f'Unable to load configuration from file "{config_file}" ...')
print(f"Unable to load configuration from file {config_file!r} ...")
print(" ... loading default configuration")
return ChemEnvConfig()
16 changes: 8 additions & 8 deletions pymatgen/analysis/chemenv/utils/func_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def __init__(self, function, options_dict=None):
:param options_dict: Dictionary containing the parameters for the ratio function.
"""
if function not in self.ALLOWED_FUNCTIONS:
raise ValueError(f'Function "{function}" is not allowed in RatioFunction of type "{type(self).__name__}"')
raise ValueError(f'Function {function!r} is not allowed in RatioFunction of type "{type(self).__name__}"')
self.eval = object.__getattribute__(self, function)
self.function = function
self.setup_parameters(options_dict=options_dict)
Expand All @@ -67,26 +67,26 @@ def setup_parameters(self, options_dict):
if len(function_options) == 1:
opts = f'Option "{function_options[0]}"'
else:
opts1 = ", ".join(f'"{op}"' for op in function_options[:-1])
opts1 = ", ".join(f"{op!r}" for op in function_options[:-1])
opts = f'Options {opts1} and "{function_options[-1]}"'
if options_dict is None or len(options_dict) == 0:
missing = "no option was provided."
else:
optgiven = list(options_dict)
if len(options_dict) == 1:
missing = f'only "{optgiven[0]}" was provided.'
missing = f"only {optgiven[0]!r} was provided."
else:
missing1 = ", ".join(f'"{miss}"' for miss in optgiven[:-1])
missing = f'only {missing1} and "{optgiven[-1]}" were provided.'
missing1 = ", ".join(f"{miss!r}" for miss in optgiven[:-1])
missing = f"only {missing1} and {optgiven[-1]!r} were provided."
raise ValueError(
f'{opts} should be provided for function "{self.function}" in RatioFunction of '
f'type "{type(self).__name__}" while {missing}'
f"{opts} should be provided for function {self.function!r} in RatioFunction of "
f"type {type(self).__name__!r} while {missing}"
)
# Setup the options and raise an error if a wrong option is provided
for key, val in options_dict.items():
if key not in function_options:
raise ValueError(
f'Option "{key}" not allowed for function "{self.function}" in RatioFunction of '
f"Option {key!r} not allowed for function {self.function!r} in RatioFunction of "
f'type "{type(self).__name__}"'
)
setattr(self, key, val)
Expand Down
Loading

0 comments on commit 582cb83

Please sign in to comment.