From 7743ac715cba914394c703194b4c581c9f4e88b8 Mon Sep 17 00:00:00 2001 From: "Haoyu (Daniel) YANG" Date: Fri, 13 Sep 2024 18:58:13 +0800 Subject: [PATCH 1/2] (Not) Use `setup-uv` in CI tests workflow (#4063) * push a random commit to get a baseline * install native micromamba + native uv * trigger uv to run a second time, hopefully cached * get a benchmark of pip install uv * remove manual install of build dependencies * more verbose uv * remove debug output --- .github/workflows/test.yml | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 13631b0285d..ba8c3db7f0c 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -68,25 +68,22 @@ jobs: run: | micromamba create -n pmg python=${{ matrix.config.python }} --yes - - name: Install uv - run: micromamba run -n pmg pip install uv - - name: Install ubuntu-only conda dependencies if: matrix.config.os == 'ubuntu-latest' run: | micromamba install -n pmg -c conda-forge bader enumlib openff-toolkit packmol pygraphviz tblite --yes - - name: Install pymatgen and dependencies + - name: Install pymatgen and dependencies via uv run: | micromamba activate pmg + pip install uv + # TODO1 (use uv over pip) uv install torch is flaky, track #3826 # TODO2 (pin torch version): DGL library (matgl) doesn't support torch > 2.2.1, # see: https://discuss.dgl.ai/t/filenotfounderror-cannot-find-dgl-c-graphbolt-library/4302 pip install torch==2.2.1 - uv pip install cython setuptools wheel - uv pip install --editable '.[${{ matrix.config.extras }}]' --resolution=${{ matrix.config.resolution }} - name: Install optional Ubuntu dependencies From 60464fd87e66b85a395b2e9d916812b406a24828 Mon Sep 17 00:00:00 2001 From: Janosh Riebesell Date: Fri, 13 Sep 2024 14:06:53 -0400 Subject: [PATCH 2/2] Fix all `ruff` DOC202 (#4067) * fix all ruff DOC202 https://docs.astral.sh/ruff/rules/docstring-extraneous-returns/ * doc str format: "list[...]: List of ..." -> "list[...]: ..." --- pyproject.toml | 4 ---- src/pymatgen/alchemy/filters.py | 23 +++++++++++-------- src/pymatgen/alchemy/materials.py | 4 ++-- src/pymatgen/alchemy/transmuters.py | 8 +++---- src/pymatgen/analysis/adsorption.py | 6 ++--- src/pymatgen/analysis/bond_valence.py | 6 ++--- .../connectivity/connected_components.py | 3 --- .../coordination_environments/voronoi.py | 12 +++++----- src/pymatgen/analysis/interfaces/zsl.py | 4 ++-- src/pymatgen/analysis/piezo_sensitivity.py | 20 ++++++++-------- src/pymatgen/core/composition.py | 2 +- src/pymatgen/ext/matproj_legacy.py | 10 ++++---- src/pymatgen/io/fiesta.py | 21 ++++++----------- src/pymatgen/io/icet.py | 12 ++++------ src/pymatgen/io/vasp/outputs.py | 6 ++--- .../advanced_transformations.py | 3 --- 16 files changed, 63 insertions(+), 81 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 260da0441ef..da140f80709 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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*"] diff --git a/src/pymatgen/alchemy/filters.py b/src/pymatgen/alchemy/filters.py index 984e4cfe175..ccb37a817cf 100644 --- a/src/pymatgen/alchemy/filters.py +++ b/src/pymatgen/alchemy/filters.py @@ -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 @@ -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) diff --git a/src/pymatgen/alchemy/materials.py b/src/pymatgen/alchemy/materials.py index c5bded7c26b..3309b157c48 100644 --- a/src/pymatgen/alchemy/materials.py +++ b/src/pymatgen/alchemy/materials.py @@ -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. """ @@ -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: diff --git a/src/pymatgen/alchemy/transmuters.py b/src/pymatgen/alchemy/transmuters.py index 69049f53493..0a55e5169c6 100644 --- a/src/pymatgen/alchemy/transmuters.py +++ b/src/pymatgen/alchemy/transmuters.py @@ -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__( @@ -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__. @@ -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 @@ -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: diff --git a/src/pymatgen/analysis/adsorption.py b/src/pymatgen/analysis/adsorption.py index 71fc08abc71..0b906ce4193 100644 --- a/src/pymatgen/analysis/adsorption.py +++ b/src/pymatgen/analysis/adsorption.py @@ -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 @@ -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 diff --git a/src/pymatgen/analysis/bond_valence.py b/src/pymatgen/analysis/bond_valence.py index 97541da6d7b..fdfb897aa28 100644 --- a/src/pymatgen/analysis/bond_valence.py +++ b/src/pymatgen/analysis/bond_valence.py @@ -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 diff --git a/src/pymatgen/analysis/chemenv/connectivity/connected_components.py b/src/pymatgen/analysis/chemenv/connectivity/connected_components.py index 1cfc55fe871..adb7f01479c 100644 --- a/src/pymatgen/analysis/chemenv/connectivity/connected_components.py +++ b/src/pymatgen/analysis/chemenv/connectivity/connected_components.py @@ -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 diff --git a/src/pymatgen/analysis/chemenv/coordination_environments/voronoi.py b/src/pymatgen/analysis/chemenv/coordination_environments/voronoi.py index e0cbaccda1f..4f030a52bea 100644 --- a/src/pymatgen/analysis/chemenv/coordination_environments/voronoi.py +++ b/src/pymatgen/analysis/chemenv/coordination_environments/voronoi.py @@ -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, } ) @@ -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, } ) diff --git a/src/pymatgen/analysis/interfaces/zsl.py b/src/pymatgen/analysis/interfaces/zsl.py index 204cd5a2533..d838f2bfaf0 100644 --- a/src/pymatgen/analysis/interfaces/zsl.py +++ b/src/pymatgen/analysis/interfaces/zsl.py @@ -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 @@ -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 diff --git a/src/pymatgen/analysis/piezo_sensitivity.py b/src/pymatgen/analysis/piezo_sensitivity.py index 36cf10b5348..50cd3e10232 100644 --- a/src/pymatgen/analysis/piezo_sensitivity.py +++ b/src/pymatgen/analysis/piezo_sensitivity.py @@ -178,16 +178,16 @@ 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: @@ -195,8 +195,7 @@ def get_IST_operations(self, opstol=1e-3): 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) @@ -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 diff --git a/src/pymatgen/core/composition.py b/src/pymatgen/core/composition.py index d772480bedf..47984444451 100644 --- a/src/pymatgen/core/composition.py +++ b/src/pymatgen/core/composition.py @@ -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. """ diff --git a/src/pymatgen/ext/matproj_legacy.py b/src/pymatgen/ext/matproj_legacy.py index 7a9a1c50030..4e6cca8e4e9 100644 --- a/src/pymatgen/ext/matproj_legacy.py +++ b/src/pymatgen/ext/matproj_legacy.py @@ -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 @@ -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 @@ -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. @@ -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] diff --git a/src/pymatgen/io/fiesta.py b/src/pymatgen/io/fiesta.py index 5ae7d972f40..97814687b90 100644 --- a/src/pymatgen/io/fiesta.py +++ b/src/pymatgen/io/fiesta.py @@ -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") diff --git a/src/pymatgen/io/icet.py b/src/pymatgen/io/icet.py index 70620edef36..00d866b3a88 100644 --- a/src/pymatgen/io/icet.py +++ b/src/pymatgen/io/icet.py @@ -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`") @@ -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.""" diff --git a/src/pymatgen/io/vasp/outputs.py b/src/pymatgen/io/vasp/outputs.py index 6b7f9f5272b..c4cef04d8e9 100644 --- a/src/pymatgen/io/vasp/outputs.py +++ b/src/pymatgen/io/vasp/outputs.py @@ -2486,10 +2486,8 @@ def read_cs_core_contribution(self) -> None: self.data["cs_core_contribution"] = core_contrib def read_cs_raw_symmetrized_tensors(self) -> None: - """Parse the matrix form of NMR tensor before corrected to table. - - Returns: - nsymmetrized tensors list in the order of atoms. + """Parse the matrix form of NMR tensor before corrected to table + and set as self.data["unsym_cs_tensor"]. """ header_pattern = r"\s+-{50,}\s+\s+Absolute Chemical Shift tensors\s+\s+-{50,}$" first_part_pattern = r"\s+UNSYMMETRIZED TENSORS\s+$" diff --git a/src/pymatgen/transformations/advanced_transformations.py b/src/pymatgen/transformations/advanced_transformations.py index 28a9750dc73..ba2f03d6349 100644 --- a/src/pymatgen/transformations/advanced_transformations.py +++ b/src/pymatgen/transformations/advanced_transformations.py @@ -1370,9 +1370,6 @@ def __init__( will be removed. Default to 0.7. quick_gen (bool): whether to quickly generate a supercell, if set to true, no need to find the smallest cell. - - Returns: - Grain boundary structure (gb (Structure) object). """ self.rotation_axis = rotation_axis self.rotation_angle = rotation_angle