Skip to content

Commit

Permalink
ruff . --fix (#3176)
Browse files Browse the repository at this point in the history
64 cases of RUF015 and PERF102
  • Loading branch information
janosh authored Jul 22, 2023
1 parent f9f2508 commit 9122d21
Show file tree
Hide file tree
Showing 30 changed files with 67 additions and 67 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ ci:

repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.278
rev: v0.0.279
hooks:
- id: ruff
args: [--fix]
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/analysis/adsorption.py
Original file line number Diff line number Diff line change
Expand Up @@ -558,7 +558,7 @@ def substitute(site, i):
props = self.slab.site_properties
if sub_both_sides:
# Find an equivalent site on the other surface
eq_indices = [indices for indices in sym_slab.equivalent_indices if i in indices][0]
eq_indices = next(indices for indices in sym_slab.equivalent_indices if i in indices)
for ii in eq_indices:
if f"{sym_slab[ii].frac_coords[2]:.6f}" != f"{site.frac_coords[2]:.6f}":
props["surface_properties"][ii] = "substitute"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -665,7 +665,7 @@ def elastic_centered_graph(self, start_node=None):
# Loop on start_nodes, sometimes some nodes cannot be elastically taken
# inside the cell if you start from a specific node
ntest_nodes = 0
start_node = list(self.graph.nodes())[0]
start_node = next(iter(self.graph.nodes()))

ntest_nodes += 1
centered_connected_subgraph = nx.MultiGraph()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -872,7 +872,7 @@ def test_coordination_sequences(self):
assert len(ccs_all) == 1
cc_oct = ccs_oct[0]
cc_all = ccs_all[0]
cc_oct_node = list(cc_oct.graph.nodes())[0]
cc_oct_node = next(iter(cc_oct.graph.nodes()))
cseq = cc_oct.coordination_sequence(source_node=cc_oct_node, path_size=6)
assert cseq == {1: 6, 2: 18, 3: 38, 4: 66, 5: 102, 6: 146}
cc_all_oct_node = next(n for n in cc_all.graph.nodes() if n.coordination_environment == "O:6")
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/analysis/chemenv/utils/scripts_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def draw_cg(
else:
faces = cg.faces(neighbors)
edges = cg.edges(neighbors)
symbol = list(site.species)[0].symbol
symbol = next(iter(site.species)).symbol
if faces_color_override:
mycolor = faces_color_override
else:
Expand Down Expand Up @@ -233,7 +233,7 @@ def compute_environments(chemenv_configuration):
source_type = questions[test]
else:
found = False
source_type = list(questions.values())[0]
source_type = next(iter(questions.values()))
if found and len(questions) > 1:
input_source = test
if source_type == "cif":
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/analysis/dimensionality.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ def get_structure_components(
components = []
for graph in comp_graphs:
dimensionality, vertices = calculate_dimensionality_of_site(
bonded_structure, list(graph.nodes())[0], inc_vertices=True
bonded_structure, next(iter(graph.nodes())), inc_vertices=True
)

component = {"dimensionality": dimensionality}
Expand Down Expand Up @@ -267,7 +267,7 @@ def zero_d_graph_to_molecule_graph(bonded_structure, graph):
seen_indices = []
sites = []

start_index = list(graph.nodes())[0]
start_index = next(iter(graph.nodes()))
queue = [(start_index, (0, 0, 0), bonded_structure.structure[start_index])]
while len(queue) > 0:
comp_i, image_i, site_i = queue.pop(0)
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/analysis/graphs.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,7 +401,7 @@ def add_edge(

# ensure that the first non-zero jimage index is positive
# assumes that at least one non-zero index is present
is_positive = [idx for idx in to_jimage if idx != 0][0] > 0
is_positive = next(idx for idx in to_jimage if idx != 0) > 0

if not is_positive:
# let's flip the jimage,
Expand Down
6 changes: 3 additions & 3 deletions pymatgen/analysis/local_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -1459,15 +1459,15 @@ def get_nn_info(self, structure: Structure, n: int):
siw = []

# Get only the atom of interest
site_atom = [
site_atom = next(
a
for i, a in enumerate(openbabel.OBMolAtomDFSIter(obmol))
if [a.GetX(), a.GetY(), a.GetZ()] == list(structure[n].coords)
][0]
)

for neighbor in openbabel.OBAtomAtomIter(site_atom):
coords = [neighbor.GetX(), neighbor.GetY(), neighbor.GetZ()]
site = [a for a in structure if list(a.coords) == coords][0]
site = next(a for a in structure if list(a.coords) == coords)
index = structure.index(site)

bond = site_atom.GetBond(neighbor)
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/analysis/structure_prediction/dopant_predictor.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ def get_dopants_from_substitution_probabilities(structure, num_dopants=5, thresh
subs = [
{
"probability": pred["probability"],
"dopant_species": list(pred["substitutions"])[0],
"original_species": list(pred["substitutions"].values())[0],
"dopant_species": next(iter(pred["substitutions"])),
"original_species": next(iter(pred["substitutions"].values())),
}
for species_preds in subs
for pred in species_preds
Expand Down
8 changes: 4 additions & 4 deletions pymatgen/analysis/surface_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ def __init__(
self.label = label
self.adsorbates = adsorbates if adsorbates else []
self.clean_entry = clean_entry
self.ads_entries_dict = {str(list(ads.composition.as_dict())[0]): ads for ads in self.adsorbates}
self.ads_entries_dict = {str(next(iter(ads.composition.as_dict()))): ads for ads in self.adsorbates}
self.mark = marker
self.color = color

Expand Down Expand Up @@ -199,14 +199,14 @@ def surface_energy(self, ucell_entry, ref_entries=None):
ucell_entry_comp = ucell_entry.composition.reduced_composition.as_dict()
slab_clean_comp = Composition({el: slab_comp[el] for el in ucell_entry_comp})
if slab_clean_comp.reduced_composition != ucell_entry.composition.reduced_composition:
list_els = [list(entry.composition.as_dict())[0] for entry in ref_entries]
list_els = [next(iter(entry.composition.as_dict())) for entry in ref_entries]
if not any(el in list_els for el in ucell_entry.composition.as_dict()):
warnings.warn("Elemental references missing for the non-dopant species.")

gamma = (Symbol("E_surf") - Symbol("Ebulk")) / (2 * Symbol("A"))
ucell_comp = ucell_entry.composition
ucell_reduced_comp = ucell_comp.reduced_composition
ref_entries_dict = {str(list(ref.composition.as_dict())[0]): ref for ref in ref_entries}
ref_entries_dict = {str(next(iter(ref.composition.as_dict()))): ref for ref in ref_entries}
ref_entries_dict.update(self.ads_entries_dict)

# Calculate Gibbs free energy of the bulk per unit formula
Expand Down Expand Up @@ -613,7 +613,7 @@ def area_frac_vs_chempot_plot(
axes = plt.gca()

for hkl in self.all_slab_entries:
clean_entry = list(self.all_slab_entries[hkl])[0]
clean_entry = next(iter(self.all_slab_entries[hkl]))
# Ignore any facets that never show up on the
# Wulff shape regardless of chemical potential
if all(a == 0 for a in hkl_area_dict[hkl]):
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/analysis/tests/test_phase_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -374,7 +374,7 @@ def test_get_phase_separation_energy(self):

duplicate_entry = PDEntry("Li2O", -14.31361175)
scaled_dup_entry = PDEntry("Li4O2", -14.31361175 * 2)
stable_entry = [e for e in self.pd.stable_entries if e.name == "Li2O"][0]
stable_entry = next(e for e in self.pd.stable_entries if e.name == "Li2O")

assert self.pd.get_phase_separation_energy(duplicate_entry) == self.pd.get_phase_separation_energy(
stable_entry
Expand Down
16 changes: 8 additions & 8 deletions pymatgen/analysis/tests/test_surface_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def test_surface_energy(self):
self.assert_all_close(float(se), manual_se, 10)

# The (111) facet should be the most stable
clean111_entry = list(self.Cu_entry_dict[(1, 1, 1)])[0]
clean111_entry = next(iter(self.Cu_entry_dict[(1, 1, 1)]))
se_Cu111 = clean111_entry.surface_energy(self.Cu_ucell_entry)
assert min(all_se) == se_Cu111

Expand Down Expand Up @@ -212,19 +212,19 @@ def test_get_surface_equilibrium(self):
# For clean stoichiometric system, the two equations should
# be parallel because the surface energy is a constant. Then
# get_surface_equilibrium should return None
clean111_entry = list(self.Cu_entry_dict[(1, 1, 1)])[0]
clean100_entry = list(self.Cu_entry_dict[(1, 0, 0)])[0]
clean111_entry = next(iter(self.Cu_entry_dict[(1, 1, 1)]))
clean100_entry = next(iter(self.Cu_entry_dict[(1, 0, 0)]))
soln = self.Cu_analyzer.get_surface_equilibrium([clean111_entry, clean100_entry])
assert not soln

# For adsorbed system, we should find one intercept
Pt_entries = self.metals_O_entry_dict["Pt"]
clean = list(Pt_entries[(1, 1, 1)])[0]
clean = next(iter(Pt_entries[(1, 1, 1)]))
ads = Pt_entries[(1, 1, 1)][clean][0]
Pt_analyzer = self.Oads_analyzer_dict["Pt"]
soln = Pt_analyzer.get_surface_equilibrium([clean, ads])

assert list(soln.values())[0] != list(soln.values())[1]
assert next(iter(soln.values())) != list(soln.values())[1]

# Check if the number of parameters for adsorption are correct
assert (Symbol("delu_O"), Symbol("gamma")) == tuple(soln)
Expand Down Expand Up @@ -424,7 +424,7 @@ def load_O_adsorption():
for el, val in metals_O_entry_dict.items():
if el in k:
if "111" in k:
clean = list(val[(1, 1, 1)])[0]
clean = next(iter(val[(1, 1, 1)]))
ads = SlabEntry(
entry.structure,
entry.energy,
Expand All @@ -435,7 +435,7 @@ def load_O_adsorption():
)
metals_O_entry_dict[el][(1, 1, 1)][clean] = [ads]
if "110" in k:
clean = list(val[(1, 1, 0)])[0]
clean = next(iter(val[(1, 1, 0)]))
ads = SlabEntry(
entry.structure,
entry.energy,
Expand All @@ -446,7 +446,7 @@ def load_O_adsorption():
)
metals_O_entry_dict[el][(1, 1, 0)][clean] = [ads]
if "100" in k:
clean = list(val[(1, 0, 0)])[0]
clean = next(iter(val[(1, 0, 0)]))
ads = SlabEntry(
entry.structure,
entry.energy,
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/command_line/tests/test_critic2_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ def test_properties_to_from_dict(self):
def test_graph_output(self):
sg = self.c2o.structure_graph()
assert str(sg.structure[3].specie) == "Xbcp"
assert set(list(sg.graph.edges(data=True))[0][2]) == {
assert set(next(iter(sg.graph.edges(data=True)))[2]) == {
"to_jimage",
"weight",
"field",
Expand Down
8 changes: 4 additions & 4 deletions pymatgen/core/bonds.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@ def get_bond_order(self, tol: float = 0.2, default_bl: float | None = None) -> f
Float value of bond order. For example, for C-C bond in
benzene, return 1.7.
"""
sp1 = list(self.site1.species)[0]
sp2 = list(self.site2.species)[0]
sp1 = next(iter(self.site1.species))
sp2 = next(iter(self.site2.species))
dist = self.site1.distance(self.site2)
return get_bond_order(sp1, sp2, dist, tol, default_bl)

Expand All @@ -93,8 +93,8 @@ def is_bonded(site1, site2, tol: float = 0.2, bond_order: float | None = None, d
Returns:
Boolean indicating whether two sites are bonded.
"""
sp1 = list(site1.species)[0]
sp2 = list(site2.species)[0]
sp1 = next(iter(site1.species))
sp2 = next(iter(site2.species))
dist = site1.distance(site2)
syms = tuple(sorted([sp1.symbol, sp2.symbol]))
if syms in bond_lengths:
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/core/periodic_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -1266,7 +1266,7 @@ def get_shannon_radius(
radii = self._el.data["Shannon radii"]
radii = radii[str(int(self._oxi_state))][cn] # type: ignore
if len(radii) == 1:
key, data = list(radii.items())[0]
key, data = next(iter(radii.items()))
if key != spin:
warnings.warn(
f"Specified {spin=} not consistent with database spin of {key}. "
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/core/sites.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ def distance_from_point(self, pt) -> float:
def species_string(self) -> str:
"""String representation of species on the site."""
if self.is_ordered:
return str(list(self.species)[0])
return str(next(iter(self.species)))
sorted_species = sorted(self.species)
return ", ".join(f"{sp}:{self.species[sp]:.3f}" for sp in sorted_species)

Expand All @@ -170,7 +170,7 @@ def specie(self) -> Element | Species | DummySpecies:
"""
if not self.is_ordered:
raise AttributeError("specie property only works for ordered sites!")
return list(self.species)[0]
return next(iter(self.species))

@property
def is_ordered(self) -> bool:
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/core/structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -2157,7 +2157,7 @@ def interpolate(

if len(unmapped_start_ind) == 1:
i = unmapped_start_ind[0]
j = list(set(range(len(start_coords))) - set(matched))[0] # type: ignore
j = next(iter(set(range(len(start_coords))) - set(matched))) # type: ignore
sorted_end_coords[i] = end_coords[j]

end_coords = sorted_end_coords
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/core/tensors.py
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,7 @@ def get_ieee_rotation(structure, refine_rotation=True):
n_umask = np.logical_not(angles == angles[u_index])
rotation[1] = get_uvec(vecs[u_index])
# Shorter of remaining lattice vectors for c axis
c = [vec / mag for (mag, vec) in sorted(zip(lengths[n_umask], vecs[n_umask]))][0]
c = next(vec / mag for (mag, vec) in sorted(zip(lengths[n_umask], vecs[n_umask])))
rotation[2] = np.array(c)
rotation[0] = np.cross(rotation[1], rotation[2])

Expand Down
2 changes: 1 addition & 1 deletion pymatgen/electronic_structure/bandstructure.py
Original file line number Diff line number Diff line change
Expand Up @@ -635,7 +635,7 @@ def from_dict(cls, dct):
labels_dict = {k.strip(): v for k, v in dct["labels_dict"].items()}
projections = {}
structure = None
if isinstance(list(dct["bands"].values())[0], dict):
if isinstance(next(iter(dct["bands"].values())), dict):
eigenvals = {Spin(int(k)): np.array(dct["bands"][k]["data"]) for k in dct["bands"]}
else:
eigenvals = {Spin(int(k)): dct["bands"][k] for k in dct["bands"]}
Expand Down
6 changes: 3 additions & 3 deletions pymatgen/electronic_structure/boltztrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -927,7 +927,7 @@ def check_acc_bzt_bands(sbs_bz, sbs_ref, warn_thr=(0.03, 0.03)):
else:
bnd_around_efermi = []
delta = 0
spin = list(sbs_bz.bands)[0]
spin = next(iter(sbs_bz.bands))
while len(bnd_around_efermi) < 8 and delta < 100:
delta += 0.1
bnd_around_efermi = []
Expand Down Expand Up @@ -1605,13 +1605,13 @@ def get_complete_dos(self, structure: Structure, analyzer_for_second_spin=None):
cdos=an_up.get_complete_dos(bs.structure,an_dw)
"""
pdoss: dict[PeriodicSite, dict[Orbital, dict[Spin, ArrayLike]]] = {}
spin_1 = list(self.dos.densities)[0]
spin_1 = next(iter(self.dos.densities))

if analyzer_for_second_spin:
if not np.all(self.dos.energies == analyzer_for_second_spin.dos.energies):
raise BoltztrapError("Dos merging error: energies of the two dos are different")

spin_2 = list(analyzer_for_second_spin.dos.densities)[0]
spin_2 = next(iter(analyzer_for_second_spin.dos.densities))
if spin_1 == spin_2:
raise BoltztrapError("Dos merging error: spin component are the same")

Expand Down
4 changes: 2 additions & 2 deletions pymatgen/electronic_structure/boltztrap2.py
Original file line number Diff line number Diff line change
Expand Up @@ -320,11 +320,11 @@ def __init__(self, vrun_obj=None):
self.atoms = AseAtomsAdaptor.get_atoms(self.structure)
self.proj = None
if len(vrun_obj.eigenvalues) == 1:
e = list(vrun_obj.eigenvalues.values())[0]
e = next(iter(vrun_obj.eigenvalues.values()))
self.ebands = e[:, :, 0].transpose() * units.eV
self.dosweight = 2.0
if vrun_obj.projected_eigenvalues:
self.proj = list(vrun_obj.projected_eigenvalues.values())[0]
self.proj = next(iter(vrun_obj.projected_eigenvalues.values()))

elif len(vrun_obj.eigenvalues) == 2:
raise BoltztrapError("spin bs case not implemented")
Expand Down
10 changes: 5 additions & 5 deletions pymatgen/electronic_structure/plotter.py
Original file line number Diff line number Diff line change
Expand Up @@ -617,7 +617,7 @@ def get_plot(
handles = []
vbm_min, cbm_max = [], []

colors = list(plt.rcParams["axes.prop_cycle"].by_key().values())[0]
colors = next(iter(plt.rcParams["axes.prop_cycle"].by_key().values()))
for ibs, bs in enumerate(self._bs):
# set first bs in the list as ref for rescaling the distances of the other bands
bs_ref = self._bs[0] if len(self._bs) > 1 and ibs > 0 else None
Expand Down Expand Up @@ -1871,7 +1871,7 @@ def _number_of_subfigures(self, dictio, dictpa, sum_atoms, sum_morbs):
_sites = self._bs.structure.sites
indices = []
for i in range(0, len(_sites)): # pylint: disable=C0200
if list(_sites[i]._species)[0] == Element(elt):
if next(iter(_sites[i]._species)) == Element(elt):
indices.append(i + 1)
for number in dictpa[elt]:
if isinstance(number, str):
Expand Down Expand Up @@ -1918,7 +1918,7 @@ def _number_of_subfigures(self, dictio, dictpa, sum_atoms, sum_morbs):
_sites = self._bs.structure.sites
indices = []
for i in range(0, len(_sites)): # pylint: disable=C0200
if list(_sites[i]._species)[0] == Element(elt):
if next(iter(_sites[i]._species)) == Element(elt):
indices.append(i + 1)
for number in sum_atoms[elt]:
if isinstance(number, str):
Expand Down Expand Up @@ -2042,7 +2042,7 @@ def orbital_label(list_orbitals):
_sites = self._bs.structure.sites
indices = []
for i in range(0, len(_sites)): # pylint: disable=C0200
if list(_sites[i]._species)[0] == Element(elt):
if next(iter(_sites[i]._species)) == Element(elt):
indices.append(i + 1)
flag_1 = len(set(dictpa[elt]).intersection(indices))
flag_2 = len(set(sum_atoms[elt]).intersection(indices))
Expand Down Expand Up @@ -2091,7 +2091,7 @@ def orbital_label(list_orbitals):
_sites = self._bs.structure.sites
indices = []
for i in range(0, len(_sites)): # pylint: disable=C0200
if list(_sites[i]._species)[0] == Element(elt):
if next(iter(_sites[i]._species)) == Element(elt):
indices.append(i + 1)
flag_1 = len(set(dictpa[elt]).intersection(indices))
flag_2 = len(set(sum_atoms[elt]).intersection(indices))
Expand Down
Loading

0 comments on commit 9122d21

Please sign in to comment.