Skip to content

Commit

Permalink
format "Returns:" doc strings for dicts
Browse files Browse the repository at this point in the history
  • Loading branch information
janosh committed May 1, 2024
1 parent c1a610c commit 28bd5df
Show file tree
Hide file tree
Showing 12 changed files with 30 additions and 41 deletions.
20 changes: 10 additions & 10 deletions pymatgen/alchemy/transmuters.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -90,17 +90,17 @@ 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.
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.
Expand All @@ -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
Expand Down
3 changes: 1 addition & 2 deletions pymatgen/analysis/interface_reactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 6 additions & 5 deletions pymatgen/analysis/phase_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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])
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/analysis/wulff.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/core/composition.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()}
Expand Down Expand Up @@ -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 = ""
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/core/ion.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

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 @@ -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, ...]:
Expand Down
6 changes: 3 additions & 3 deletions pymatgen/electronic_structure/cohp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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():
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/io/lammps/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
15 changes: 2 additions & 13 deletions pymatgen/io/nwchem.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/io/vasp/outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion tests/core/test_lattice.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down

0 comments on commit 28bd5df

Please sign in to comment.