Skip to content

Commit

Permalink
Fix all ruff DOC202 (#4067)
Browse files Browse the repository at this point in the history
* fix all ruff DOC202

https://docs.astral.sh/ruff/rules/docstring-extraneous-returns/

* doc str format: "list[...]: List of ..." -> "list[...]: ..."
  • Loading branch information
janosh authored Sep 13, 2024
1 parent 7743ac7 commit 60464fd
Show file tree
Hide file tree
Showing 16 changed files with 63 additions and 81 deletions.
4 changes: 0 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -165,10 +165,6 @@ include = ["pymatgen", "pymatgen.*"]
lint = ["mypy>=1.10.0", "pre-commit>=3.7.1", "ruff>=0.4.9"]
test = ["pytest-cov>=5.0.0", "pytest-split>=0.9.0", "pytest>=8.2.2"]

[tool.versioningit.vcs]
method = "git"
default-tag = "0.0.1"

[tool.cibuildwheel.linux]
archs = ["auto64"]
skip = ["*musllinux*"]
Expand Down
23 changes: 14 additions & 9 deletions src/pymatgen/alchemy/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,16 +214,21 @@ def get_spg_num(struct: Structure) -> int:
class RemoveExistingFilter(AbstractStructureFilter):
"""This filter removes structures existing in a given list from the transmuter."""

def __init__(self, existing_structures, structure_matcher=None, symprec=None):
def __init__(
self,
existing_structures: list[Structure],
structure_matcher: dict | StructureMatcher | None = None,
symprec: float | None = None,
) -> None:
"""Remove existing structures based on the structure matcher
and symmetry (if symprec is given).
Args:
existing_structures: List of existing structures to compare with
structure_matcher: Provides a structure matcher to be used for
existing_structures (list[Structure]): Existing structures to compare with.
structure_matcher (dict | StructureMatcher, optional): Will be used for
structure comparison.
symprec: The precision in the symmetry finder algorithm if None (
default value), no symmetry check is performed and only the
symprec (float | None): The precision in the symmetry finder algorithm.
If None (default value), no symmetry check is performed and only the
structure matcher is used. A recommended value is 1e-5.
"""
self.symprec = symprec
Expand All @@ -241,15 +246,15 @@ def get_sg(s):
finder = SpacegroupAnalyzer(s, symprec=self.symprec)
return finder.get_space_group_number()

for s in self.existing_structures:
for struct in self.existing_structures:
if (
(
self.structure_matcher._comparator.get_hash(structure.composition)
== self.structure_matcher._comparator.get_hash(s.composition)
== self.structure_matcher._comparator.get_hash(struct.composition)
and self.symprec is None
)
or get_sg(s) == get_sg(structure)
) and self.structure_matcher.fit(s, structure):
or get_sg(struct) == get_sg(structure)
) and self.structure_matcher.fit(struct, structure):
return False

self.structure_list.append(structure)
Expand Down
4 changes: 2 additions & 2 deletions src/pymatgen/alchemy/materials.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def __init__(
Args:
structure (Structure): Input structure
transformations (list[Transformation]): List of transformations to apply.
transformations (list[Transformation]): Transformations to apply.
history (list[Transformation]): Previous history.
other_parameters (dict): Additional parameters to be added.
"""
Expand Down Expand Up @@ -355,7 +355,7 @@ def to_snl(self, authors: list[str], **kwargs) -> StructureNL:
"""Generate a StructureNL from TransformedStructure.
Args:
authors (List[str]): List of authors contributing to the generated StructureNL.
authors (List[str]): Authors contributing to the generated StructureNL.
**kwargs (Any): All kwargs supported by StructureNL.
Returns:
Expand Down
8 changes: 4 additions & 4 deletions src/pymatgen/alchemy/transmuters.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class StandardTransmuter:
transformations on many structures to generate TransformedStructures.
Attributes:
transformed_structures (list[Structure]): List of all transformed structures.
transformed_structures (list[Structure]): All transformed structures.
"""

def __init__(
Expand Down Expand Up @@ -262,7 +262,7 @@ def from_filenames(cls, filenames, transformations=None, primitive=True, extend_
containing multiple structures.
Args:
filenames: List of strings of the CIF files
filenames (list[str]): The CIF file paths.
transformations: New transformations to be applied to all
structures
primitive: Same meaning as in __init__.
Expand All @@ -286,7 +286,7 @@ class PoscarTransmuter(StandardTransmuter):
def __init__(self, poscar_string, transformations=None, extend_collection=False):
"""
Args:
poscar_string: List of POSCAR strings
poscar_string (list[str]): POSCAR strings.
transformations: New transformations to be applied to all
structures.
extend_collection: Whether to use more than one output structure
Expand All @@ -301,7 +301,7 @@ def from_filenames(cls, poscar_filenames, transformations=None, extend_collectio
POSCAR filenames.
Args:
poscar_filenames: List of POSCAR filenames
poscar_filenames (list[str]): The POSCAR file paths.
transformations: New transformations to be applied to all
structures.
extend_collection:
Expand Down
6 changes: 3 additions & 3 deletions src/pymatgen/analysis/adsorption.py
Original file line number Diff line number Diff line change
Expand Up @@ -348,8 +348,8 @@ def ensemble_center(cls, site_list, indices, cartesian=True):
sites. Helper method for the find_adsorption_sites algorithm.
Args:
site_list (list of sites): list of sites
indices (list of ints): list of ints from which to select
site_list (list[Site]): sites from which to select
indices (list[int]): indices of sites from which to select
sites from site list
cartesian (bool): whether to get average fractional or
Cartesian coordinate
Expand Down Expand Up @@ -543,7 +543,7 @@ def generate_substitution_structures(
atom (str): atom corresponding to substitutional dopant
sub_both_sides (bool): If true, substitute an equivalent
site on the other surface
target_species (list): List of specific species to substitute
target_species (list): Specific species to substitute
range_tol (float): Find viable substitution sites at a specific
distance from the surface +- this tolerance
dist_from_surf (float): Distance from the surface to find viable
Expand Down
6 changes: 3 additions & 3 deletions src/pymatgen/analysis/bond_valence.py
Original file line number Diff line number Diff line change
Expand Up @@ -460,18 +460,18 @@ def get_z_ordered_elmap(comp):
return sorted((elem, comp[elem]) for elem in comp)


def add_oxidation_state_by_site_fraction(structure, oxidation_states):
def add_oxidation_state_by_site_fraction(structure: Structure, oxidation_states: list[list[int]]) -> Structure:
"""
Add oxidation states to a structure by fractional site.
Args:
oxidation_states (list): List of list of oxidation states for each
oxidation_states (list[list[int]]): List of list of oxidation states for each
site fraction for each site.
e.g. [[2, 4], [3], [-2], [-2], [-2]]
"""
try:
for idx, site in enumerate(structure):
new_sp = defaultdict(float)
new_sp: dict[Species, float] = defaultdict(float)
for j, (el, occu) in enumerate(get_z_ordered_elmap(site.species)):
specie = Species(el.symbol, oxidation_states[idx][j])
new_sp[specie] += occu
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,9 +211,6 @@ def __init__(
environments_data: Data of environment nodes.
links_data: Data of links between environment nodes.
graph: Graph of the connected component.
Returns:
ConnectedComponent: Instance of this class
"""
self._periodicity_vectors: list[list] | None = None
self._primitive_reduced_connected_subgraph = None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -563,14 +563,14 @@ def maps_and_surfaces(
maps_and_surfaces = []
for cn, value in self._unique_coordinated_neighbors_parameters_indices[isite].items():
for imap, list_parameters_indices in enumerate(value):
thissurf = 0.0
this_surf = 0.0
for idp, iap, iacb in list_parameters_indices:
if iacb in additional_conditions:
thissurf += surfaces[idp, iap]
this_surf += surfaces[idp, iap]
maps_and_surfaces.append(
{
"map": (cn, imap),
"surface": thissurf,
"surface": this_surf,
"parameters_indices": list_parameters_indices,
}
)
Expand All @@ -596,14 +596,14 @@ def maps_and_surfaces_bounded(self, isite, surface_calculation_options=None, add
maps_and_surfaces = []
for cn, value in self._unique_coordinated_neighbors_parameters_indices[isite].items():
for imap, list_parameters_indices in enumerate(value):
thissurf = 0.0
this_surf = 0.0
for idp, iap, iacb in list_parameters_indices:
if iacb in additional_conditions:
thissurf += surfaces[idp, iap]
this_surf += surfaces[idp, iap]
maps_and_surfaces.append(
{
"map": (cn, imap),
"surface": thissurf,
"surface": this_surf,
"parameters_indices": list_parameters_indices,
}
)
Expand Down
4 changes: 2 additions & 2 deletions src/pymatgen/analysis/interfaces/zsl.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ def __init__(
self.max_angle_tol = max_angle_tol
self.bidirectional = bidirectional

def generate_sl_transformation_sets(self, film_area, substrate_area):
def generate_sl_transformation_sets(self, film_area: int, substrate_area: int) -> Iterator[tuple]:
"""Generate transformation sets for film/substrate pair given the
area of the unit cell area for the film and substrate. The
transformation sets map the film and substrate unit cells to super
Expand All @@ -118,7 +118,7 @@ def generate_sl_transformation_sets(self, film_area, substrate_area):
film_area (int): the unit cell area for the film
substrate_area (int): the unit cell area for the substrate
Returns:
Yields:
transformation_sets: a set of transformation_sets defined as:
1.) the transformation matrices for the film to create a
super lattice of area i*film area
Expand Down
20 changes: 10 additions & 10 deletions src/pymatgen/analysis/piezo_sensitivity.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,25 +178,24 @@ def __init__(self, structure: Structure, ist, pointops, tol: float = 1e-3):
self.structure = structure
self.ist = ist
self.pointops = pointops
self.IST_operations = None
self.IST_operations: list[list[list]] = []

obj = self.ist
if not (obj - np.transpose(obj, (0, 1, 3, 2)) < tol).all():
warnings.warn("Input internal strain tensor does not satisfy standard symmetries")

def get_IST_operations(self, opstol=1e-3):
def get_IST_operations(self, opstol=1e-3) -> list[list[list]]:
"""Get the symmetry operations which maps the tensors
belonging to equivalent sites onto each other in the form
[site index 1, site index 2, [Symmops mapping from site
[site index 1, site index 2, [SymmOps mapping from site
index 1 to site index 2]].
Args:
opstol (float): tolerance for determining if a symmetry
operation relates two sites
Returns:
list of symmetry operations mapping equivalent sites and
the indexes of those sites.
list[list[list]]: symmetry operations mapping equivalent sites and the indexes of those sites.
"""
struct = self.structure
ops = SpacegroupAnalyzer(struct).get_symmetry_operations(cartesian=True)
Expand All @@ -207,18 +206,19 @@ def get_IST_operations(self, opstol=1e-3):
if op not in uniq_point_ops:
uniq_point_ops.append(op)

IST_operations = []
for atom in range(len(self.ist)):
IST_operations: list[list[list]] = []
for atom_idx in range(len(self.ist)):
IST_operations.append([])
for j in range(atom):
for j in range(atom_idx):
for op in uniq_point_ops:
new = op.transform_tensor(self.ist[j])

# Check the matrix it references
if np.allclose(new, self.ist[atom], atol=opstol):
IST_operations[atom].append([j, op])
if np.allclose(new, self.ist[atom_idx], atol=opstol):
IST_operations[atom_idx].append([j, op])

self.IST_operations = IST_operations
return IST_operations

def get_rand_IST(self, max_force=1):
"""Generate a random internal strain tensor which obeys a structure's
Expand Down
2 changes: 1 addition & 1 deletion src/pymatgen/core/composition.py
Original file line number Diff line number Diff line change
Expand Up @@ -1099,7 +1099,7 @@ def _comps_from_fuzzy_formula(
factor: Coefficient for this parse, e.g. (PO4)2 will feed in PO4
as the fuzzy_formula with a coefficient of 2.
Returns:
Yields:
list[tuple[Composition, int]]: A list of tuples, with the first element being a Composition
and the second element being the number of points awarded that Composition interpretation.
"""
Expand Down
10 changes: 5 additions & 5 deletions src/pymatgen/ext/matproj_legacy.py
Original file line number Diff line number Diff line change
Expand Up @@ -1035,7 +1035,7 @@ def submit_structures(
data=None,
histories=None,
created_at=None,
):
) -> list[str]:
"""Submits a list of structures to the Materials Project as SNL files.
The argument list mirrors the arguments for the StructureNL object,
except that a list of structures with the same metadata is used as an
Expand Down Expand Up @@ -1065,7 +1065,7 @@ def submit_structures(
created_at (datetime): A datetime object
Returns:
A list of inserted submission ids.
list[str]: Inserted submission ids.
"""
from pymatgen.util.provenance import StructureNL

Expand All @@ -1079,7 +1079,7 @@ def submit_structures(
histories,
created_at,
)
self.submit_snl(snl_list)
return self.submit_snl(snl_list)

def submit_snl(self, snl):
"""Submits a list of StructureNL to the Materials Project site.
Expand All @@ -1093,10 +1093,10 @@ def submit_snl(self, snl):
of StructureNL objects
Returns:
A list of inserted submission ids.
list[str]: Inserted submission ids.
Raises:
MPRestError
MPRestError: If submission fails.
"""
snl = snl if isinstance(snl, list) else [snl]
json_data = [s.as_dict() for s in snl]
Expand Down
21 changes: 7 additions & 14 deletions src/pymatgen/io/fiesta.py
Original file line number Diff line number Diff line change
Expand Up @@ -382,25 +382,18 @@ def set_bse_options(self, n_excitations=10, nit_bse=200):
self.bse_tddft_options.update(npsi_bse=n_excitations, nit_bse=nit_bse)

def dump_bse_data_in_gw_run(self, BSE_dump=True):
"""
Args:
BSE_dump: bool.
"""Set the "do_bse" variable to 1 or 0 in cell.in.
Returns:
set the "do_bse" variable to one in cell.in
Args:
BSE_dump (bool): Defaults to True.
"""
if BSE_dump:
self.bse_tddft_options.update(do_bse=1, do_tddft=0)
else:
self.bse_tddft_options.update(do_bse=0, do_tddft=0)
self.bse_tddft_options.update(do_bse=int(BSE_dump), do_tddft=0)

def dump_tddft_data_in_gw_run(self, tddft_dump: bool = True):
"""
Args:
TDDFT_dump: bool.
"""Set the do_tddft variable to 1 or 0 in cell.in.
Returns:
set the do_tddft variable to one in cell.in
Args:
tddft_dump (bool): Defaults to True.
"""
self.bse_tddft_options.update(do_bse="0", do_tddft="1" if tddft_dump else "0")

Expand Down
12 changes: 4 additions & 8 deletions src/pymatgen/io/icet.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,6 @@ def __init__(
"monte carlo" otherwise.
sqs_kwargs (dict): kwargs to pass to the icet SQS generators.
See self.sqs_kwarg_names for possible options.
Returns:
None
"""
if ClusterSpace is None:
raise ImportError("IcetSQS requires the icet package. Use `pip install icet`")
Expand Down Expand Up @@ -173,25 +170,24 @@ def run(self) -> Sqs:
clusters=str(self._get_cluster_space()),
)

def _get_site_composition(self) -> None:
def _get_site_composition(self) -> dict[str, dict]:
"""Get Icet-format composition from structure.
Returns:
Dict with sublattice compositions specified by uppercase letters,
e.g. In_x Ga_1-x As becomes:
{
e.g. In_x Ga_1-x As becomes: {
"A": {"In": x, "Ga": 1 - x},
"B": {"As": 1}
}
"""
uppercase_letters = list(ascii_uppercase)
idx = 0
self.composition: dict[str, dict] = {}
for idx, site in enumerate(self._structure):
site_comp = site.species.as_dict()
if site_comp not in self.composition.values():
self.composition[uppercase_letters[idx]] = site_comp
idx += 1

return self.composition

def _get_cluster_space(self) -> ClusterSpace:
"""Generate the ClusterSpace object for icet."""
Expand Down
Loading

0 comments on commit 60464fd

Please sign in to comment.