From 28bd5df28c88701592ff15d699d584c59db3c918 Mon Sep 17 00:00:00 2001 From: Janosh Riebesell Date: Tue, 30 Apr 2024 20:40:11 -0400 Subject: [PATCH] format "Returns:" doc strings for dicts --- pymatgen/alchemy/transmuters.py | 20 ++++++++++---------- pymatgen/analysis/interface_reactions.py | 3 +-- pymatgen/analysis/phase_diagram.py | 11 ++++++----- pymatgen/analysis/wulff.py | 2 +- pymatgen/core/composition.py | 4 ++-- pymatgen/core/ion.py | 2 +- pymatgen/core/periodic_table.py | 2 +- pymatgen/electronic_structure/cohp.py | 6 +++--- pymatgen/io/lammps/utils.py | 2 +- pymatgen/io/nwchem.py | 15 ++------------- pymatgen/io/vasp/outputs.py | 2 +- tests/core/test_lattice.py | 2 +- 12 files changed, 30 insertions(+), 41 deletions(-) diff --git a/pymatgen/alchemy/transmuters.py b/pymatgen/alchemy/transmuters.py index 606e749411d..ceb85d986ec 100644 --- a/pymatgen/alchemy/transmuters.py +++ b/pymatgen/alchemy/transmuters.py @@ -73,15 +73,15 @@ def __getitem__(self, index): return self.transformed_structures[index] def __getattr__(self, name): - return [getattr(x, name) for x in self.transformed_structures] + return [getattr(ts, name) for ts in self.transformed_structures] def __len__(self): return len(self.transformed_structures) def __str__(self): output = ["Current structures", "------------"] - for x in self.transformed_structures: - output.append(str(x.final_structure)) + for ts in self.transformed_structures: + output.append(str(ts.final_structure)) return "\n".join(output) def undo_last_change(self) -> None: @@ -90,8 +90,8 @@ def undo_last_change(self) -> None: Raises: IndexError if already at the oldest change. """ - for x in self.transformed_structures: - x.undo_last_change() + for ts in self.transformed_structures: + ts.undo_last_change() def redo_next_change(self) -> None: """Redo the last undone transformation in the TransformedStructure. @@ -99,8 +99,8 @@ def redo_next_change(self) -> None: Raises: IndexError if already at the latest change. """ - for x in self.transformed_structures: - x.redo_next_change() + for ts in self.transformed_structures: + ts.redo_next_change() def append_transformation(self, transformation, extend_collection=False, clear_redo=True): """Append a transformation to all TransformedStructures. @@ -122,15 +122,15 @@ def append_transformation(self, transformation, extend_collection=False, clear_r if self.ncores and transformation.use_multiprocessing: with Pool(self.ncores) as p: # need to condense arguments into single tuple to use map - z = ((x, transformation, extend_collection, clear_redo) for x in self.transformed_structures) + z = ((ts, transformation, extend_collection, clear_redo) for ts in self.transformed_structures) trafo_new_structs = p.map(_apply_transformation, z, 1) self.transformed_structures = [] for ts in trafo_new_structs: self.transformed_structures.extend(ts) else: new_structures = [] - for x in self.transformed_structures: - new = x.append_transformation(transformation, extend_collection, clear_redo=clear_redo) + for ts in self.transformed_structures: + new = ts.append_transformation(transformation, extend_collection, clear_redo=clear_redo) if new is not None: new_structures += new self.transformed_structures += new_structures diff --git a/pymatgen/analysis/interface_reactions.py b/pymatgen/analysis/interface_reactions.py index e3d093082c9..764408c6ab0 100644 --- a/pymatgen/analysis/interface_reactions.py +++ b/pymatgen/analysis/interface_reactions.py @@ -187,8 +187,7 @@ def get_kinks(self) -> list[tuple[int, float, float, Reaction, float]]: def plot(self, backend: Literal["plotly", "matplotlib"] = "plotly") -> Figure | plt.Figure: """ - Plots reaction energy as a function of mixing ratio x in self.c1 - self.c2 - tie line. + Plots reaction energy as a function of mixing ratio x in self.c1 - self.c2 tie line. Args: backend ("plotly" | "matplotlib"): Plotting library used to create the plot. Defaults to diff --git a/pymatgen/analysis/phase_diagram.py b/pymatgen/analysis/phase_diagram.py index 75d029b0b08..069105fb980 100644 --- a/pymatgen/analysis/phase_diagram.py +++ b/pymatgen/analysis/phase_diagram.py @@ -632,15 +632,15 @@ def _get_all_facets_and_simplexes(self, comp): return all_facets - def _get_facet_chempots(self, facet): + def _get_facet_chempots(self, facet: list[int]) -> dict[Element, float]: """ Calculates the chemical potentials for each element within a facet. Args: - facet: Facet of the phase diagram. + facet (list): Indices of the entries in the facet. Returns: - {element: chempot} for all elements in the phase diagram. + dict[Element, float]: Chemical potentials for each element in the facet. """ comp_list = [self.qhull_entries[idx].composition for idx in facet] energy_list = [self.qhull_entries[idx].energy_per_atom for idx in facet] @@ -1255,8 +1255,9 @@ def get_chempot_range_stability_phase(self, target_comp, open_elt): open_elt: Element that you want to constrain to be max or min Returns: - {Element: (mu_min, mu_max)}: Chemical potentials are given in - "absolute" values (i.e., not referenced to 0) + dict[Element, (float, float)]: A dictionary of the form {Element: (min_mu, max_mu)} + where min_mu and max_mu are the minimum and maximum chemical potentials + for the given element (as "absolute" values, i.e. not referenced to 0). """ mu_ref = np.array([self.el_refs[elem].energy_per_atom for elem in self.elements if elem != open_elt]) chempot_ranges = self.get_chempot_range_map([elem for elem in self.elements if elem != open_elt]) diff --git a/pymatgen/analysis/wulff.py b/pymatgen/analysis/wulff.py index 6a1b537e320..d553d382e0e 100644 --- a/pymatgen/analysis/wulff.py +++ b/pymatgen/analysis/wulff.py @@ -159,7 +159,7 @@ def __init__(self, lattice: Lattice, miller_list, e_surf_list, symprec=1e-5): logger.debug(len(self.facets)) # 3. consider the dual condition - dual_pts = [x.dual_pt for x in self.facets] + dual_pts = [facet.dual_pt for facet in self.facets] dual_convex = ConvexHull(dual_pts) dual_cv_simp = dual_convex.simplices # simplices (ndarray of ints, shape (n_facet, n_dim)) diff --git a/pymatgen/core/composition.py b/pymatgen/core/composition.py index c66955c938a..842d9d97705 100644 --- a/pymatgen/core/composition.py +++ b/pymatgen/core/composition.py @@ -377,7 +377,7 @@ def get_reduced_formula_and_factor(self, iupac_ordering: bool = False) -> tuple[ A pretty normalized formula and a multiplicative factor, i.e., Li4Fe4P4O16 returns (LiFePO4, 4). """ - all_int = all(abs(x - round(x)) < Composition.amount_tolerance for x in self.values()) + all_int = all(abs(val - round(val)) < Composition.amount_tolerance for val in self.values()) if not all_int: return self.formula.replace(" ", ""), 1 el_amt_dict = {key: int(round(val)) for key, val in self.get_el_amt_dict().items()} @@ -578,7 +578,7 @@ def anonymized_formula(self) -> str: anonymized_formula ABC3. """ reduced = self.element_composition - if all(x == int(x) for x in self.values()): + if all(val == int(val) for val in self.values()): reduced /= gcd(*(int(i) for i in self.values())) anon = "" diff --git a/pymatgen/core/ion.py b/pymatgen/core/ion.py index 017b1963877..050009d33de 100644 --- a/pymatgen/core/ion.py +++ b/pymatgen/core/ion.py @@ -124,7 +124,7 @@ def get_reduced_formula_and_factor(self, iupac_ordering: bool = False, hydrates: tuple[str, float]: A pretty normalized formula and a multiplicative factor, i.e., H4O4 returns ('H2O2', 2.0). """ - all_int = all(abs(x - round(x)) < Composition.amount_tolerance for x in self.values()) + all_int = all(abs(val - round(val)) < Composition.amount_tolerance for val in self.values()) if not all_int: return self.formula.replace(" ", ""), 1 diff --git a/pymatgen/core/periodic_table.py b/pymatgen/core/periodic_table.py index 29f7154c40a..f75d8dc8830 100644 --- a/pymatgen/core/periodic_table.py +++ b/pymatgen/core/periodic_table.py @@ -361,7 +361,7 @@ def min_oxidation_state(self) -> float: @property def oxidation_states(self) -> tuple[int, ...]: """Tuple of all known oxidation states.""" - return tuple(int(x) for x in self._data.get("Oxidation states", [])) + return tuple(map(int, self._data.get("Oxidation states", []))) @property def common_oxidation_states(self) -> tuple[int, ...]: diff --git a/pymatgen/electronic_structure/cohp.py b/pymatgen/electronic_structure/cohp.py index 252ae4c24f0..d27d142a5f0 100644 --- a/pymatgen/electronic_structure/cohp.py +++ b/pymatgen/electronic_structure/cohp.py @@ -163,7 +163,7 @@ def has_antibnd_states_below_efermi(self, spin=None, limit=0.01): limit: -COHP smaller -limit will be considered. """ populations = self.cohp - n_energies_below_efermi = len([x for x in self.energies if x <= self.efermi]) + n_energies_below_efermi = len([energy for energy in self.energies if energy <= self.efermi]) if populations is None: return None @@ -1020,10 +1020,10 @@ def summed_icohp(self): @property def summed_orbital_icohp(self): - """Sums orbitals-resolved ICOHPs of both spin channels for spin-plarized compounds. + """Sums orbital-resolved ICOHPs of both spin channels for spin-polarized compounds. Returns: - {"str(Orbital1)-str(Ortibal2)": icohp value in eV}. + dict[str, float]: "str(Orbital1)-str(Ortibal2)" mapped to ICOHP value in eV. """ orbital_icohp = {} for orb, item in self._orbitals.items(): diff --git a/pymatgen/io/lammps/utils.py b/pymatgen/io/lammps/utils.py index 64670889fb0..b3de443cd44 100644 --- a/pymatgen/io/lammps/utils.py +++ b/pymatgen/io/lammps/utils.py @@ -418,7 +418,7 @@ def restore_site_properties(self, site_property: str = "ff_map", filename: str | bma = BabelMolAdaptor.from_file(filename, "pdb") pbm = pybel.Molecule(bma._ob_mol) - assert len(pbm.residues) == sum(x["number"] for x in self.param_list) + assert len(pbm.residues) == sum(param["number"] for param in self.param_list) packed_mol = self.convert_obatoms_to_molecule( pbm.residues[0].atoms, diff --git a/pymatgen/io/nwchem.py b/pymatgen/io/nwchem.py index c7382876c2a..02fa6c8053d 100644 --- a/pymatgen/io/nwchem.py +++ b/pymatgen/io/nwchem.py @@ -570,19 +570,8 @@ def parse_tddft(self): Parses TDDFT roots. Adapted from nw_spectrum.py script. Returns: - { - "singlet": [ - { - "energy": float, - "osc_strength: float - } - ], - "triplet": [ - { - "energy": float - } - ] - } + dict[str, list]: A dict of the form {"singlet": [dict, ...], "triplet": [dict, ...]} where + each sub-dict is of the form {"energy": float, "osc_strength": float}. """ start_tag = "Convergence criterion met" end_tag = "Excited state energy" diff --git a/pymatgen/io/vasp/outputs.py b/pymatgen/io/vasp/outputs.py index 51a9eb570d1..5075542cd9c 100644 --- a/pymatgen/io/vasp/outputs.py +++ b/pymatgen/io/vasp/outputs.py @@ -4191,7 +4191,7 @@ def get_str(self, ionicstep_start: int = 1, ionicstep_end: int | None = None, si if np.linalg.det(lattice.matrix) < 0: lattice = Lattice(-lattice.matrix) lines = [self.comment, "1.0", str(lattice)] - lines.extend((" ".join(self.site_symbols), " ".join(str(x) for x in self.natoms))) + lines.extend((" ".join(self.site_symbols), " ".join(map(str, self.natoms)))) format_str = f"{{:.{significant_figures}f}}" ionicstep_cnt = 1 output_cnt = 1 diff --git a/tests/core/test_lattice.py b/tests/core/test_lattice.py index 943085f1bdb..9c9594b90ff 100644 --- a/tests/core/test_lattice.py +++ b/tests/core/test_lattice.py @@ -51,7 +51,7 @@ def test_equal(self): assert (name1 == name2) == (latt1 == latt2) # ensure partial periodic boundaries is unequal to all full periodic boundaries - assert not any(self.cubic_partial_pbc == x for x in self.families.values()) + assert not any(self.cubic_partial_pbc == family for family in self.families.values()) def test_format(self): assert (