Skip to content

Commit

Permalink
fix PLR5501: collapsible-else-if
Browse files Browse the repository at this point in the history
Consider using elif instead of else then if to remove one indentation level
  • Loading branch information
janosh committed May 6, 2023
1 parent 7737862 commit 525fc26
Show file tree
Hide file tree
Showing 35 changed files with 342 additions and 413 deletions.
2 changes: 1 addition & 1 deletion dev_scripts/chemenv/get_plane_permutations_optimized.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ def random_permutations_iterator(initial_permutation, n_permutations):
if test == "y":
break
elif test == "q":
exit()
raise SystemExit(0)
# 2. Optimization of the permutations
print(f"Getting explicit optimized permutations for geometry {cg.name!r} (symbol : {cg_symbol!r})\n")
perms_used_algos = [{} for algo in cg.algorithms]
Expand Down
11 changes: 5 additions & 6 deletions pymatgen/analysis/bond_dissociation.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,12 @@ def __init__(
self.expected_charges = [final_charge, final_charge + 1]
else:
self.expected_charges = [final_charge - 1, final_charge]
elif final_charge == 0:
self.expected_charges = [-2, -1, 0, 1, 2]
elif final_charge < 0:
self.expected_charges = [final_charge - 1, final_charge, final_charge + 1, final_charge + 2]
else:
if final_charge == 0:
self.expected_charges = [-2, -1, 0, 1, 2]
elif final_charge < 0:
self.expected_charges = [final_charge - 1, final_charge, final_charge + 1, final_charge + 2]
else:
self.expected_charges = [final_charge - 2, final_charge - 1, final_charge, final_charge + 1]
self.expected_charges = [final_charge - 2, final_charge - 1, final_charge, final_charge + 1]

# Build principle molecule graph
self.mol_graph = MoleculeGraph.with_local_env_strategy(
Expand Down
11 changes: 5 additions & 6 deletions pymatgen/analysis/chemenv/connectivity/connected_components.py
Original file line number Diff line number Diff line change
Expand Up @@ -724,13 +724,12 @@ def elastic_centered_graph(self, start_node=None):
if edata["delta"] == (0, 0, 0):
already_inside = True
thisdelta = edata["delta"]
elif edata["start"] == node.isite and edata["end"] != node.isite:
thisdelta = edata["delta"]
elif edata["end"] == node.isite:
thisdelta = tuple(-dd for dd in edata["delta"])
else:
if edata["start"] == node.isite and edata["end"] != node.isite:
thisdelta = edata["delta"]
elif edata["end"] == node.isite:
thisdelta = tuple(-dd for dd in edata["delta"])
else:
raise ValueError("Should not be here ...")
raise ValueError("Should not be here ...")
ddeltas.append(thisdelta)
logging.debug(
" ddeltas : " + ", ".join(f"({', '.join(str(ddd) for ddd in dd)})" for dd in ddeltas)
Expand Down
72 changes: 35 additions & 37 deletions pymatgen/analysis/chemenv/connectivity/structure_connectivity.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,27 +120,26 @@ def add_bonds(self, isite, site_neighbors_set):
if np.allclose(data1["delta"], np.zeros(3)) and nb_index_unitcell == ineighb1:
exists = True
break
elif isite == nb_index_unitcell:
for isite1, ineighb1, data1 in existing_edges:
if isite1 == ineighb1 and (
np.allclose(data1["delta"], nb_image_cell) or np.allclose(data1["delta"], -nb_image_cell)
):
exists = True
break
else:
if isite == nb_index_unitcell:
for isite1, ineighb1, data1 in existing_edges:
if isite1 == ineighb1 and (
np.allclose(data1["delta"], nb_image_cell) or np.allclose(data1["delta"], -nb_image_cell)
):
exists = True
break
else:
for _, ineighb1, data1 in existing_edges:
if nb_index_unitcell == ineighb1:
if data1["start"] == isite:
if np.allclose(data1["delta"], nb_image_cell):
exists = True
break
elif data1["end"] == isite:
if np.allclose(data1["delta"], -nb_image_cell):
exists = True
break
else:
raise ValueError("SHOULD NOT HAPPEN ???")
for _, ineighb1, data1 in existing_edges:
if nb_index_unitcell == ineighb1:
if data1["start"] == isite:
if np.allclose(data1["delta"], nb_image_cell):
exists = True
break
elif data1["end"] == isite:
if np.allclose(data1["delta"], -nb_image_cell):
exists = True
break
else:
raise ValueError("SHOULD NOT HAPPEN ???")
if not exists:
self._graph.add_edge(
isite,
Expand Down Expand Up @@ -187,30 +186,29 @@ def setup_environment_subgraph(self, environments_symbols, only_atoms=None):
ce_this_site,
)
self._environment_subgraph.add_node(env_node)
elif self.light_structure_environments.structure.is_ordered:
if self.light_structure_environments.structure[isite].specie.symbol in only_atoms:
env_node = get_environment_node(
self.light_structure_environments.structure[isite],
isite,
ce_this_site,
)
self._environment_subgraph.add_node(env_node)
else:
if self.light_structure_environments.structure.is_ordered:
if self.light_structure_environments.structure[isite].specie.symbol in only_atoms:
# TODO: add the possibility of a "constraint" on the minimum percentage
# of the atoms on the site
this_site_elements = [
sp.symbol for sp in self.light_structure_environments.structure[isite].species_and_occu
]
for elem_symbol in this_site_elements:
if elem_symbol in only_atoms:
env_node = get_environment_node(
self.light_structure_environments.structure[isite],
isite,
ce_this_site,
)
self._environment_subgraph.add_node(env_node)
else:
# TODO: add the possibility of a "constraint" on the minimum percentage
# of the atoms on the site
this_site_elements = [
sp.symbol for sp in self.light_structure_environments.structure[isite].species_and_occu
]
for elem_symbol in this_site_elements:
if elem_symbol in only_atoms:
env_node = get_environment_node(
self.light_structure_environments.structure[isite],
isite,
ce_this_site,
)
self._environment_subgraph.add_node(env_node)
break
break
# Find the connections between the environments
nodes = list(self._environment_subgraph.nodes())
for inode1, node1 in enumerate(nodes):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1350,17 +1350,12 @@ def __init__(self, average_type, aa, bb):
self.fda = self.ang
else:
self.fda = self.angn
elif self.aa == 1:
self.fda = self.anginvdist if self.bb == 1 else self.anginvndist
elif self.bb == 1:
self.fda = self.angninvdist
else:
if self.aa == 1:
if self.bb == 1:
self.fda = self.anginvdist
else:
self.fda = self.anginvndist
else:
if self.bb == 1:
self.fda = self.angninvdist
else:
self.fda = self.angninvndist
self.fda = self.angninvndist

def __eq__(self, other: object) -> bool:
needed_attrs = ("average_type", "aa", "bb")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -519,16 +519,15 @@ def compute_coordination_environments(
vals = bva.get_valences(structure=structure)
except ValueError:
vals = "undefined"
elif valences == "undefined":
vals = valences
else:
if valences == "undefined":
vals = valences
else:
len_vals, len_sites = len(valences), len(structure)
if len_vals != len_sites:
raise ValueError(
f"Valences ({len_vals}) do not match the number of sites in the structure ({len_sites})"
)
vals = valences
len_vals, len_sites = len(valences), len(structure)
if len_vals != len_sites:
raise ValueError(
f"Valences ({len_vals}) do not match the number of sites in the structure ({len_sites})"
)
vals = valences
# TODO: add something to compute only the neighbors sets needed for the strategy.
se = self.compute_structure_environments(
only_cations=only_cations,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1581,9 +1581,8 @@ def from_structure_environments(cls, strategy, structure_environments, valences=
valences = structure_environments.valences
if valences_origin is None:
valences_origin = "from_structure_environments"
else:
if valences_origin is None:
valences_origin = "user-specified"
elif valences_origin is None:
valences_origin = "user-specified"

for isite, site in enumerate(structure):
site_ces_and_nbs_list = strategy.get_site_ce_fractions_and_neighbors(site, strategy_info=True)
Expand Down
29 changes: 13 additions & 16 deletions pymatgen/analysis/chemenv/utils/coordination_geometry_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,13 +215,12 @@ def diamond_functions(xx, yy, y_x0, x_y0):
else:
p1 = npyy
p2 = npxx
elif npxx[0] < npyy[0]:
p1 = npxx
p2 = npyy
else:
if npxx[0] < npyy[0]:
p1 = npxx
p2 = npyy
else:
p1 = npyy
p2 = npxx
p1 = npyy
p2 = npxx
slope = (p2[1] - p1[1]) / (p2[0] - p1[0])
if slope > 0.0:
x_bpoint = p1[0] + x_y0
Expand Down Expand Up @@ -326,12 +325,11 @@ def rectangle_surface_intersection(
"Function f_lower is not always lower or equal to function f_upper within "
"the domain defined by the functions bounds."
)
else:
if "<" not in function_comparison(f1=f_lower, f2=f_upper, x1=x1, x2=x2, numpoints_check=numpoints_check):
raise RuntimeError(
"Function f_lower is not always lower or equal to function f_upper within "
"the domain defined by x1 and x2."
)
elif "<" not in function_comparison(f1=f_lower, f2=f_upper, x1=x1, x2=x2, numpoints_check=numpoints_check):
raise RuntimeError(
"Function f_lower is not always lower or equal to function f_upper within "
"the domain defined by x1 and x2."
)
if bounds_lower is None:
raise NotImplementedError("Bounds should be given right now ...")
if x2 < bounds_lower[0] or x1 > bounds_lower[1]:
Expand Down Expand Up @@ -716,11 +714,10 @@ def indices_separate(self, points, dist_tolerance):
for ip, pp in enumerate(points):
if self.is_in_plane(pp, dist_tolerance):
inplane.append(ip)
elif np.dot(pp + self.vector_to_origin, self.normal_vector) < 0.0:
side1.append(ip)
else:
if np.dot(pp + self.vector_to_origin, self.normal_vector) < 0.0:
side1.append(ip)
else:
side2.append(ip)
side2.append(ip)
return [side1, inplane, side2]

def distance_to_point(self, point):
Expand Down
34 changes: 15 additions & 19 deletions pymatgen/analysis/chemenv/utils/graph_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,36 +97,32 @@ def _c2index_isreverse(c1, c2):
elif c2_1_index == len(c2.nodes) - 1:
reverse = True
else:
return (
None,
None,
msg = (
"Second node of cycle c1 is not second or last in cycle c2 "
"(first node of cycle c1 is first in cycle c2).",
"(first node of cycle c1 is first in cycle c2)."
)
return None, None, msg
elif c2_0_index == len(c2.nodes) - 1:
if c2_1_index == 0:
reverse = False
elif c2_1_index == c2_0_index - 1:
reverse = True
else:
return (
None,
None,
msg = (
"Second node of cycle c1 is not first or before last in cycle c2 "
"(first node of cycle c1 is last in cycle c2).",
"(first node of cycle c1 is last in cycle c2)."
)
return None, None, msg
elif c2_1_index == c2_0_index + 1:
reverse = False
elif c2_1_index == c2_0_index - 1:
reverse = True
else:
if c2_1_index == c2_0_index + 1:
reverse = False
elif c2_1_index == c2_0_index - 1:
reverse = True
else:
return (
None,
None,
"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
10 changes: 4 additions & 6 deletions pymatgen/analysis/functional_groups.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,8 @@ def get_heteroatoms(self, elements=None):
if elements is not None:
if str(self.species[node]) in elements:
heteroatoms.add(node)
else:
if str(self.species[node]) not in ["C", "H"]:
heteroatoms.add(node)
elif str(self.species[node]) not in ["C", "H"]:
heteroatoms.add(node)

return heteroatoms

Expand Down Expand Up @@ -149,9 +148,8 @@ def get_special_carbon(self, elements=None):
if elements is not None:
if str(self.species[neighbor]) in elements and int(attributes[0]["weight"]) in [2, 3]:
specials.add(node)
else:
if str(self.species[neighbor]) not in ["C", "H"] and int(attributes[0]["weight"]) in [2, 3]:
specials.add(node)
elif str(self.species[neighbor]) not in ["C", "H"] and int(attributes[0]["weight"]) in [2, 3]:
specials.add(node)

# Condition two: carbon-carbon double & triple bonds
for node in carbons:
Expand Down
9 changes: 4 additions & 5 deletions pymatgen/analysis/gb/grain.py
Original file line number Diff line number Diff line change
Expand Up @@ -2140,11 +2140,10 @@ def slab_from_csl(csl, surface, normal, trans_cry, max_search=20, quick_gen=Fals
c_norm = c_norm_temp
normal_init = True
t_matrix[2] = temp
else:
if c_len_temp < c_length or (abs(c_len_temp - c_length) < 1.0e-8 and c_norm_temp < c_norm):
t_matrix[2] = temp
c_norm = c_norm_temp
c_length = c_len_temp
elif c_len_temp < c_length or (abs(c_len_temp - c_length) < 1.0e-8 and c_norm_temp < c_norm):
t_matrix[2] = temp
c_norm = c_norm_temp
c_length = c_len_temp

if normal and (not normal_init):
logger.info("Did not find the perpendicular c vector, increase max_j")
Expand Down
7 changes: 3 additions & 4 deletions pymatgen/analysis/local_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,11 +341,10 @@ def get_cn_dict(self, structure: Structure, n: int, use_weights: bool = False):
cn_dict[site_element] = idx["weight"]
else:
cn_dict[site_element] = 1
elif use_weights:
cn_dict[site_element] += idx["weight"]
else:
if use_weights:
cn_dict[site_element] += idx["weight"]
else:
cn_dict[site_element] += 1
cn_dict[site_element] += 1
return cn_dict

def get_nn(self, structure: Structure, n: int):
Expand Down
13 changes: 6 additions & 7 deletions pymatgen/analysis/tests/test_phase_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,13 +321,12 @@ def test_get_phase_separation_energy(self):
assert (
self.pd.get_phase_separation_energy(entry) >= 0
), "Unstable entries should have positive decomposition energy!"
else:
if entry.is_element:
el_ref = self.pd.el_refs[entry.composition.elements[0]]
e_d = entry.energy_per_atom - el_ref.energy_per_atom
assert self.pd.get_phase_separation_energy(entry) == pytest.approx(e_d)
# NOTE the remaining materials would require explicit tests as they
# could be either positive or negative
elif entry.is_element:
el_ref = self.pd.el_refs[entry.composition.elements[0]]
e_d = entry.energy_per_atom - el_ref.energy_per_atom
assert self.pd.get_phase_separation_energy(entry) == pytest.approx(e_d)
# NOTE the remaining materials would require explicit tests as they
# could be either positive or negative

for entry in self.pd.stable_entries:
if entry.composition.is_element:
Expand Down
5 changes: 2 additions & 3 deletions pymatgen/command_line/chargemol_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -404,9 +404,8 @@ def _write_jobscript_for_chargemol(
if os.name == "nt":
if atomic_densities_path[-1] != "\\":
atomic_densities_path += "\\"
else:
if atomic_densities_path[-1] != "/":
atomic_densities_path += "/"
elif atomic_densities_path[-1] != "/":
atomic_densities_path += "/"

lines += (
f"\n<atomic densities directory complete path>\n{atomic_densities_path}\n</atomic densities directory "
Expand Down
Loading

0 comments on commit 525fc26

Please sign in to comment.