diff --git a/dev_scripts/chemenv/strategies/multi_weights_strategy_parameters.py b/dev_scripts/chemenv/strategies/multi_weights_strategy_parameters.py index d8217b93162..16233f78ea6 100644 --- a/dev_scripts/chemenv/strategies/multi_weights_strategy_parameters.py +++ b/dev_scripts/chemenv/strategies/multi_weights_strategy_parameters.py @@ -73,12 +73,12 @@ def simple_expansion(cls, initial_environment_symbol, expected_final_environment ) def figure_fractions(self, weights_options: dict, morphing_factors: Sequence[float] | None = None) -> None: - """ - Plot the fractions of the initial and final coordination environments as a function of the morphing factor. + """Plot the fractions of the initial and final coordination environments as a + function of the morphing factor. Args: - weights_options (dict): The weights options. - morphing_factors (list): The morphing factors. + weights_options (dict): The weights options. morphing_factors (list): The + morphing factors. """ if morphing_factors is None: morphing_factors = np.linspace(1.0, 2.0, 21) diff --git a/pymatgen/alchemy/materials.py b/pymatgen/alchemy/materials.py index 53bcd98160b..9600b52541d 100644 --- a/pymatgen/alchemy/materials.py +++ b/pymatgen/alchemy/materials.py @@ -281,7 +281,7 @@ def from_cif_str( primitive (bool): Option to set if the primitive cell should be extracted. Defaults to True. However, there are certain instances where you might want to use a non-primitive cell, - e.g., if you are trying to generate all possible orderings of + e.g. if you are trying to generate all possible orderings of partial removals or order a disordered structure. Defaults to True. occupancy_tolerance (float): If total occupancy of a site is between 1 and occupancy_tolerance, the occupancies will be @@ -352,8 +352,7 @@ def from_dict(cls, dct: dict) -> Self: return cls(struct, history=dct["history"], other_parameters=dct.get("other_parameters")) def to_snl(self, authors: list[str], **kwargs) -> StructureNL: - """ - Generate a StructureNL from TransformedStructure. + """Generate a StructureNL from TransformedStructure. Args: authors (List[str]): List of authors contributing to the generated StructureNL. diff --git a/pymatgen/alchemy/transmuters.py b/pymatgen/alchemy/transmuters.py index 59760d3505e..457187624ae 100644 --- a/pymatgen/alchemy/transmuters.py +++ b/pymatgen/alchemy/transmuters.py @@ -182,7 +182,7 @@ def add_tags(self, tags): Args: tags: A sequence of tags. Note that this should be a sequence of - strings, e.g., ["My awesome structures", "Project X"]. + strings, e.g. ["My awesome structures", "Project X"]. """ self.set_parameter("tags", tags) @@ -336,7 +336,7 @@ def batch_write_vasp_input( Defaults to True. subfolder: Function to create subdirectory name from transformed_structure. - e.g., lambda x: x.other_parameters["tags"][0] to use the first + e.g. lambda x: x.other_parameters["tags"][0] to use the first tag. include_cif (bool): Boolean indication whether to output a CIF as well. CIF files are generally better supported in visualization diff --git a/pymatgen/analysis/adsorption.py b/pymatgen/analysis/adsorption.py index c0dfbcd83f6..8521408b72d 100644 --- a/pymatgen/analysis/adsorption.py +++ b/pymatgen/analysis/adsorption.py @@ -139,7 +139,7 @@ def from_bulk_and_miller( surf_props, under_coords = [], [] this_mi_vec = get_mi_vec(this_slab) mi_mags = [np.dot(this_mi_vec, site.coords) for site in this_slab] - average_mi_mag = np.average(mi_mags) + average_mi_mag = np.mean(mi_mags) for n, site in enumerate(this_slab): bulk_coord = this_slab.site_properties["bulk_coordinations"][n] slab_coord = len(vnn_surface.get_nn(this_slab, n)) @@ -355,9 +355,9 @@ def ensemble_center(cls, site_list, indices, cartesian=True): Cartesian coordinate """ if cartesian: - return np.average([site_list[idx].coords for idx in indices], axis=0) + return np.mean([site_list[idx].coords for idx in indices], axis=0) - return np.average([site_list[idx].frac_coords for idx in indices], axis=0) + return np.mean([site_list[idx].frac_coords for idx in indices], axis=0) def add_adsorbate(self, molecule: Molecule, ads_coord, repeat=None, translate=True, reorient=True): """Add an adsorbate at a particular coordinate. Adsorbate represented diff --git a/pymatgen/analysis/bond_dissociation.py b/pymatgen/analysis/bond_dissociation.py index 89c1948042e..73b9f2d4fe2 100644 --- a/pymatgen/analysis/bond_dissociation.py +++ b/pymatgen/analysis/bond_dissociation.py @@ -44,8 +44,7 @@ def __init__( allow_additional_charge_separation: bool = False, multibreak: bool = False, ) -> None: - """ - Note that the entries passed by the user must have the following keys: formula_pretty, initial_molecule, + """The provided entries must have the following keys: formula_pretty, initial_molecule, final_molecule. If a PCM is present, all entries should also have a pcm_dielectric key. Args: @@ -327,8 +326,7 @@ def filter_fragment_entries(self, fragment_entries: list) -> None: self.filtered_entries += [entry] def build_new_entry(self, frags: list, bonds: list) -> list: - """ - Build a new entry for bond dissociation that will be returned to the user. + """Build a new entry for bond dissociation that will be returned to the user. Args: frags (list): Fragments involved in the bond dissociation. diff --git a/pymatgen/analysis/bond_valence.py b/pymatgen/analysis/bond_valence.py index c05ead701fa..bdfef485abc 100644 --- a/pymatgen/analysis/bond_valence.py +++ b/pymatgen/analysis/bond_valence.py @@ -126,8 +126,7 @@ def __init__( charge_neutrality_tolerance=CHARGE_NEUTRALITY_TOLERANCE, forbidden_species=None, ): - """ - Initializes the BV analyzer, with useful defaults. + """Initialize the BV analyzer, with useful defaults. Args: symm_tol: @@ -204,16 +203,15 @@ def _calc_site_probabilities_unordered(self, site, nn): return prob def get_valences(self, structure: Structure): - """ - Returns a list of valences for each site in the structure. + """Get a list of valences for each site in the structure. Args: structure: Structure to analyze Returns: A list of valences for each site in the structure (for an ordered structure), - e.g., [1, 1, -2] or a list of lists with the valences for each fractional - element of each site in the structure (for an unordered structure), e.g., [[2, + e.g. [1, 1, -2] or a list of lists with the valences for each fractional + element of each site in the structure (for an unordered structure), e.g. [[2, 4], [3], [-2], [-2], [-2]] Raises: @@ -469,7 +467,7 @@ def add_oxidation_state_by_site_fraction(structure, oxidation_states): Args: oxidation_states (list): List of list of oxidation states for each site fraction for each site. - E.g., [[2, 4], [3], [-2], [-2], [-2]] + e.g. [[2, 4], [3], [-2], [-2], [-2]] """ try: for idx, site in enumerate(structure): diff --git a/pymatgen/analysis/chemenv/connectivity/connected_components.py b/pymatgen/analysis/chemenv/connectivity/connected_components.py index d4e56c8520b..f68b4e2dd62 100644 --- a/pymatgen/analysis/chemenv/connectivity/connected_components.py +++ b/pymatgen/analysis/chemenv/connectivity/connected_components.py @@ -625,14 +625,14 @@ def _order_periodicity_vectors(self): @property def periodicity_vectors(self): - """Get periodicity vectors of this connected component.""" + """Periodicity vectors of this connected component.""" if self._periodicity_vectors is None: self.compute_periodicity() return [np.array(pp) for pp in self._periodicity_vectors] @property def periodicity(self): - """Get periodicity of this connected component.""" + """Periodicity of this connected component.""" if self._periodicity_vectors is None: self.compute_periodicity() return f"{len(self._periodicity_vectors)}D" diff --git a/pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py b/pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py index fb4e7417cb0..f3ad0592b86 100644 --- a/pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py +++ b/pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py @@ -196,9 +196,8 @@ def from_dict(cls, dct: dict) -> Self: class AbstractChemenvStrategy(MSONable, abc.ABC): - """ - Class used to define a Chemenv strategy for the neighbors and coordination environment to be applied to a - StructureEnvironments object. + """Base class to define a Chemenv strategy for the neighbors and coordination environment + to be applied to a StructureEnvironments object. """ AC = AdditionalConditions() diff --git a/pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py b/pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py index ed24e2150b2..e1e1701b1f5 100644 --- a/pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py +++ b/pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py @@ -13,7 +13,7 @@ import itertools import json import os -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any import numpy as np from monty.json import MontyDecoder, MSONable @@ -54,17 +54,12 @@ def __init__(self, algorithm_type): self._algorithm_type = algorithm_type @abc.abstractmethod - def as_dict(self): + def as_dict(self) -> dict[str, Any]: """A JSON-serializable dict representation of the algorithm.""" @property - def algorithm_type(self): - """ - Return the type of algorithm. - - Returns: - str: Type of the algorithm - """ + def algorithm_type(self) -> str: + """The type of algorithm.""" return self._algorithm_type @abc.abstractmethod @@ -73,8 +68,7 @@ def __str__(self): class ExplicitPermutationsAlgorithm(AbstractChemenvAlgorithm): - """ - Class representing the algorithm doing the explicit permutations for the calculation of + """Algorithm doing the explicit permutations for the calculation of the Continuous Symmetry Measure. """ @@ -91,21 +85,12 @@ def __str__(self): return self.algorithm_type @property - def permutations(self): - """ - Return the permutations to be performed for this algorithm. - - Returns: - list: Permutations to be performed. - """ + def permutations(self) -> list[list[int]]: + """Permutations to be performed for this algorithm.""" return self._permutations - @property def as_dict(self): - """ - Returns: - dict: JSON-serializable representation of this ExplicitPermutationsAlgorithm - """ + """JSON-serializable representation of this ExplicitPermutationsAlgorithm.""" return { "@module": type(self).__module__, "@class": type(self).__name__, @@ -121,8 +106,7 @@ def from_dict(cls, dct: dict) -> Self: class SeparationPlane(AbstractChemenvAlgorithm): - """ - Class representing the algorithm using separation planes for the calculation of + """Algorithm using separation planes for the calculation of the Continuous Symmetry Measure. """ @@ -196,39 +180,27 @@ def __init__( ) @property - def permutations(self): - """ - Permutations used for this separation plane algorithm. - - Returns: - list[Permutations]: to be performed. - """ + def permutations(self) -> list[list[int]]: + """List of permutations to be performed for this separation plane algorithm.""" return self._permutations @property - def ref_separation_perm(self): - """ - Ordered indices of the separation plane. + def ref_separation_perm(self) -> list[int]: + """Ordered indices of the separation plane. Examples: For a separation plane of type 2|4|3, with plane_points indices [0, 3, 5, 8] and point_groups indices [1, 4] and [2, 7, 6], the list of ordered indices is : [0, 3, 5, 8, 1, 4, 2, 7, 6]. - - Returns: - list[int]: of ordered indices of this separation plane. """ return self._ref_separation_perm @property - def argsorted_ref_separation_perm(self): + def argsorted_ref_separation_perm(self) -> list[int]: """ "Arg sorted" ordered indices of the separation plane. This is used in the identification of the final permutation to be used. - - Returns: - list[int]: "arg sorted" ordered indices of the separation plane. """ return self._argsorted_ref_separation_perm @@ -300,13 +272,10 @@ def rotate(s, n): self._safe_permutations.append(perm) return self._safe_permutations - @property def as_dict(self): """ - Return the JSON-serializable dict representation of this SeparationPlane algorithm. - Returns: - dict: JSON-serializable representation of this SeparationPlane algorithm. + dict: JSON-serializable dict representation of this SeparationPlane algorithm. """ return { "@module": type(self).__module__, @@ -524,8 +493,7 @@ def __init__( equivalent_indices=None, neighbors_sets_hints=None, ): - """ - Initializes one "coordination geometry" according to [Pure Appl. Chem., Vol. 79, No. 10, pp. 1779--1799, 2007] + """Initialize one "coordination geometry" according to [Pure Appl. Chem., Vol. 79, No. 10, pp. 1779--1799, 2007] and [Acta Cryst. A, Vol. 46, No. 1, pp. 1--11, 1990]. Args: @@ -765,8 +733,7 @@ def number_of_permutations(self): return len(self.permutations) def ref_permutation(self, permutation): - """ - Returns the reference permutation for a set of equivalent permutations. + """Get the reference permutation for a set of equivalent permutations. Can be useful to skip permutations that have already been performed. @@ -792,16 +759,14 @@ def get_central_site(self): return self.central_site def faces(self, sites, permutation=None): - """ - Returns the list of faces of this coordination geometry. Each face is given as a + """Get the list of faces of this coordination geometry. Each face is given as a list of its vertices coordinates. """ coords = [site.coords for site in sites] if permutation is None else [sites[ii].coords for ii in permutation] return [[coords[ii] for ii in face] for face in self._faces] def edges(self, sites, permutation=None, input="sites"): - """ - Returns the list of edges of this coordination geometry. Each edge is given as a + """Get the list of edges of this coordination geometry. Each edge is given as a list of its end vertices coordinates. """ if input == "sites": @@ -820,8 +785,7 @@ def edges(self, sites, permutation=None, input="sites"): return [[coords[ii] for ii in edge] for edge in self._edges] def solid_angles(self, permutation=None): - """ - Returns the list of "perfect" solid angles Each edge is given as a + """Get the list of "perfect" solid angles Each edge is given as a list of its end vertices coordinates. """ if permutation is None: @@ -830,7 +794,7 @@ def solid_angles(self, permutation=None): def get_pmeshes(self, sites, permutation=None): """Returns the pmesh strings used for jmol to show this geometry.""" - pmeshes = [] + p_meshes = [] # _vertices = [site.coords for site in sites] _vertices = [site.coords for site in sites] if permutation is None else [sites[ii].coords for ii in permutation] _face_centers = [] @@ -867,19 +831,17 @@ def get_pmeshes(self, sites, permutation=None): for face_vertex in face: out += f"{face_vertex}\n" out += f"{face[0]}\n" - pmeshes.append({"pmesh_string": out}) - return pmeshes + p_meshes.append({"pmesh_string": out}) + return p_meshes class AllCoordinationGeometries(dict): - """ - Class used to store all the reference "coordination geometries" (list with instances of the CoordinationGeometry - classes). + """Store all the reference "coordination geometries" (list with instances + of the CoordinationGeometry classes). """ def __init__(self, permutations_safe_override=False, only_symbols=None): - """ - Initializes the list of Coordination Geometries. + """Initialize the list of Coordination Geometries. Args: permutations_safe_override: Whether to use safe permutations. @@ -973,8 +935,7 @@ def __str__(self): return "\n".join(outs) def get_geometries(self, coordination=None, returned="cg"): - """ - Returns a list of coordination geometries with the given coordination number. + """Get a list of coordination geometries with the given coordination number. Args: coordination: The coordination number of which the list of coordination geometries are returned. @@ -1037,8 +998,7 @@ def get_symbol_cn_mapping(self, coordination=None): return geom def get_implemented_geometries(self, coordination=None, returned="cg", include_deactivated=False): - """ - Returns a list of the implemented coordination geometries with the given coordination number. + """Get a list of the implemented coordination geometries with the given coordination number. Args: coordination: The coordination number of which the list of implemented coordination geometries @@ -1068,8 +1028,7 @@ def get_implemented_geometries(self, coordination=None, returned="cg", include_d return geom def get_not_implemented_geometries(self, coordination=None, returned="mp_symbol"): - """ - Returns a list of the implemented coordination geometries with the given coordination number. + """Get a list of the implemented coordination geometries with the given coordination number. Args: coordination: The coordination number of which the list of implemented coordination geometries @@ -1094,8 +1053,7 @@ def get_not_implemented_geometries(self, coordination=None, returned="mp_symbol" return geom def get_geometry_from_name(self, name): - """ - Returns the coordination geometry of the given name. + """Get the coordination geometry of the given name. Args: name: The name of the coordination geometry. @@ -1106,8 +1064,7 @@ def get_geometry_from_name(self, name): raise LookupError(f"No coordination geometry found with name {name!r}") def get_geometry_from_IUPAC_symbol(self, IUPAC_symbol): - """ - Returns the coordination geometry of the given IUPAC symbol. + """Get the coordination geometry of the given IUPAC symbol. Args: IUPAC_symbol: The IUPAC symbol of the coordination geometry. @@ -1118,8 +1075,7 @@ def get_geometry_from_IUPAC_symbol(self, IUPAC_symbol): raise LookupError(f"No coordination geometry found with IUPAC symbol {IUPAC_symbol!r}") def get_geometry_from_IUCr_symbol(self, IUCr_symbol): - """ - Returns the coordination geometry of the given IUCr symbol. + """Get the coordination geometry of the given IUCr symbol. Args: IUCr_symbol: The IUCr symbol of the coordination geometry. @@ -1130,8 +1086,7 @@ def get_geometry_from_IUCr_symbol(self, IUCr_symbol): raise LookupError(f"No coordination geometry found with IUCr symbol {IUCr_symbol!r}") def get_geometry_from_mp_symbol(self, mp_symbol): - """ - Returns the coordination geometry of the given mp_symbol. + """Get the coordination geometry of the given mp_symbol. Args: mp_symbol: The mp_symbol of the coordination geometry. diff --git a/pymatgen/analysis/chemenv/coordination_environments/coordination_geometry_finder.py b/pymatgen/analysis/chemenv/coordination_environments/coordination_geometry_finder.py index 73e96d513d2..d5ff872fc4e 100644 --- a/pymatgen/analysis/chemenv/coordination_environments/coordination_geometry_finder.py +++ b/pymatgen/analysis/chemenv/coordination_environments/coordination_geometry_finder.py @@ -489,8 +489,7 @@ def setup_structure(self, structure: Structure): self.symmetrized_structure = self.spg_analyzer_refined.get_symmetrized_structure() def get_structure(self): - """ - Returns the pymatgen Structure that has been setup for the identification of geometries (the initial one + """Get the pymatgen Structure that has been setup for the identification of geometries (the initial one might have been refined/symmetrized using the SpaceGroupAnalyzer). Returns: @@ -1152,8 +1151,7 @@ def setup_explicit_indices_local_geometry(self, explicit_indices): self.indices = [ii + 1 for ii in explicit_indices] def get_coordination_symmetry_measures(self, only_minimum=True, all_csms=True, optimization=None): - """ - Returns the continuous symmetry measures of the current local geometry in a dictionary. + """Get the continuous symmetry measures of the current local geometry in a dictionary. Returns: the continuous symmetry measures of the current local geometry in a dictionary. @@ -1281,8 +1279,7 @@ def _update_results_all_csms(self, result_dict, permutations, imin, geometry): def get_coordination_symmetry_measures_optim( self, only_minimum=True, all_csms=True, nb_set=None, optimization=None ): - """ - Returns the continuous symmetry measures of the current local geometry in a dictionary. + """Get the continuous symmetry measures of the current local geometry in a dictionary. Returns: the continuous symmetry measures of the current local geometry in a dictionary. @@ -1428,8 +1425,7 @@ def coordination_geometry_symmetry_measures_sepplane_optim( def coordination_geometry_symmetry_measures_standard( self, coordination_geometry, algo, points_perfect=None, optimization=None ): - """ - Returns the symmetry measures for a set of permutations (whose setup depends on the coordination geometry) + """Get the symmetry measures for a set of permutations (whose setup depends on the coordination geometry) for the coordination geometry "coordination_geometry". Standard implementation looking for the symmetry measures of each permutation @@ -1510,8 +1506,7 @@ def coordination_geometry_symmetry_measures_separation_plane( tested_permutations=False, points_perfect=None, ): - """ - Returns the symmetry measures of the given coordination geometry "coordination_geometry" using separation + """Get the symmetry measures of the given coordination geometry "coordination_geometry" using separation facets to reduce the complexity of the system. Caller to the refined 2POINTS, 3POINTS and other ... Args: @@ -1614,8 +1609,7 @@ def coordination_geometry_symmetry_measures_separation_plane_optim( nb_set=None, optimization=None, ): - """ - Returns the symmetry measures of the given coordination geometry "coordination_geometry" using separation + """Get the symmetry measures of the given coordination geometry "coordination_geometry" using separation facets to reduce the complexity of the system. Caller to the refined 2POINTS, 3POINTS and other ... Args: @@ -2035,8 +2029,7 @@ def _cg_csm_separation_plane_optim2( def coordination_geometry_symmetry_measures_fallback_random( self, coordination_geometry, n_random=10, points_perfect=None, **kwargs ): - """ - Returns the symmetry measures for a random set of permutations for the coordination geometry + """Get the symmetry measures for a random set of permutations for the coordination geometry "coordination_geometry". Fallback implementation for the plane separation algorithms measures of each permutation diff --git a/pymatgen/analysis/chemenv/coordination_environments/structure_environments.py b/pymatgen/analysis/chemenv/coordination_environments/structure_environments.py index b74395a6c93..3047379e309 100644 --- a/pymatgen/analysis/chemenv/coordination_environments/structure_environments.py +++ b/pymatgen/analysis/chemenv/coordination_environments/structure_environments.py @@ -618,8 +618,7 @@ def get_csm(self, isite, mp_symbol): return csms[0] def get_csms(self, isite, mp_symbol) -> list: - """ - Returns the continuous symmetry measure(s) of site with index isite with respect to the + """Get the continuous symmetry measure(s) of site with index isite with respect to the perfect coordination environment with mp_symbol. For some environments, a given mp_symbol might not be available (if there is no voronoi parameters leading to a number of neighbors corresponding to the coordination number of environment mp_symbol). For some environments, a given mp_symbol might @@ -1313,8 +1312,7 @@ def from_dict(cls, dct: dict) -> Self: class LightStructureEnvironments(MSONable): - """ - Class used to store the chemical environments of a given structure obtained from a given ChemenvStrategy. Currently, + """Store the chemical environments of a given structure obtained from a given ChemenvStrategy. Currently, only strategies leading to the determination of a unique environment for each site is allowed This class does not store all the information contained in the StructureEnvironments object, only the coordination environment found. @@ -2063,14 +2061,12 @@ def from_dict(cls, dct: dict) -> Self: class ChemicalEnvironments(MSONable): - """ - Class used to store all the information about the chemical environment of a given site for a given list of + """Store all the information about the chemical environment of a given site for a given list of coordinated neighbors (internally called "cn_map"). """ def __init__(self, coord_geoms=None): - """ - Initializes the ChemicalEnvironments object containing all the information about the chemical + """Initialize the ChemicalEnvironments object containing all the information about the chemical environment of a given site. Args: @@ -2087,8 +2083,7 @@ def __getitem__(self, mp_symbol): return self.coord_geoms[mp_symbol] def __len__(self): - """ - Returns the number of coordination geometries in this ChemicalEnvironments object. + """Get the number of coordination geometries in this ChemicalEnvironments object. Returns: Number of coordination geometries in this ChemicalEnvironments object. @@ -2099,8 +2094,7 @@ def __iter__(self): yield from self.coord_geoms.items() def minimum_geometry(self, symmetry_measure_type=None, max_csm=None): - """ - Returns the geometry with the minimum continuous symmetry measure of this ChemicalEnvironments. + """Get the geometry with the minimum continuous symmetry measure of this ChemicalEnvironments. Returns: tuple (symbol, csm) with symbol being the geometry with the minimum continuous symmetry measure and @@ -2123,8 +2117,7 @@ def minimum_geometry(self, symmetry_measure_type=None, max_csm=None): return cglist[imin], csmlist[imin] def minimum_geometries(self, n=None, symmetry_measure_type=None, max_csm=None): - """ - Returns a list of geometries with increasing continuous symmetry measure in this ChemicalEnvironments object. + """Get a list of geometries with increasing continuous symmetry measure in this ChemicalEnvironments object. Args: n: Number of geometries to be included in the list. @@ -2212,8 +2205,7 @@ def add_coord_geom( } def __str__(self): - """ - Returns a string representation of the ChemicalEnvironments object. + """Get a string representation of the ChemicalEnvironments object. Returns: String representation of the ChemicalEnvironments object. @@ -2319,8 +2311,7 @@ def __eq__(self, other: object) -> bool: return True def as_dict(self): - """ - Returns a dictionary representation of the ChemicalEnvironments object. + """Get a dictionary representation of the ChemicalEnvironments object. Returns: A dictionary representation of the ChemicalEnvironments object. diff --git a/pymatgen/analysis/chemenv/coordination_environments/voronoi.py b/pymatgen/analysis/chemenv/coordination_environments/voronoi.py index 7bb55229f09..e2dae783f00 100644 --- a/pymatgen/analysis/chemenv/coordination_environments/voronoi.py +++ b/pymatgen/analysis/chemenv/coordination_environments/voronoi.py @@ -194,8 +194,7 @@ def setup_voronoi_list(self, indices, voronoi_cutoff): logging.debug(f"Voronoi list set up in {t2 - t1:.2f} seconds") def setup_neighbors_distances_and_angles(self, indices): - """ - Initializes the angle and distance separations. + """Initialize the angle and distance separations. Args: indices: Indices of the sites for which the Voronoi is needed. diff --git a/pymatgen/analysis/chemenv/utils/chemenv_config.py b/pymatgen/analysis/chemenv/utils/chemenv_config.py index 00d802054d0..92f326a0831 100644 --- a/pymatgen/analysis/chemenv/utils/chemenv_config.py +++ b/pymatgen/analysis/chemenv/utils/chemenv_config.py @@ -19,11 +19,10 @@ class ChemEnvConfig: - """ - Class used to store the configuration of the chemenv package : - - Materials project access - - ICSD database access - - Default options (strategies, ...). + """Store the configuration of the chemenv package: + - Materials project access + - ICSD database access + - Default options (strategies, ...). """ DEFAULT_PACKAGE_OPTIONS = dict( @@ -86,9 +85,7 @@ def setup(self): @property def has_materials_project_access(self): - """ - Whether MP access is enabled. - """ + """Whether MP access is enabled.""" return self.materials_project_configuration is not None def setup_package_options(self): diff --git a/pymatgen/analysis/chemenv/utils/coordination_geometry_utils.py b/pymatgen/analysis/chemenv/utils/coordination_geometry_utils.py index fcf35b52124..42d4f78df11 100644 --- a/pymatgen/analysis/chemenv/utils/coordination_geometry_utils.py +++ b/pymatgen/analysis/chemenv/utils/coordination_geometry_utils.py @@ -406,7 +406,6 @@ def vectorsToMatrix(aa, bb): def matrixTimesVector(MM, aa): """ - Args: MM: A matrix of size 3x3 aa: A vector of size 3 @@ -640,8 +639,7 @@ class Plane: ) def __init__(self, coefficients, p1=None, p2=None, p3=None): - """ - Initializes a plane from the 4 coefficients a, b, c and d of ax + by + cz + d = 0 + """Initialize a plane from the 4 coefficients a, b, c and d of ax + by + cz + d = 0 Args: coefficients: abcd coefficients of the plane. @@ -750,8 +748,7 @@ def is_in_list(self, plane_list) -> bool: return any(self.is_same_plane_as(plane) for plane in plane_list) def indices_separate(self, points, dist_tolerance): - """ - Returns three lists containing the indices of the points lying on one side of the plane, on the plane + """Get three lists containing the indices of the points lying on one side of the plane, on the plane and on the other side of the plane. The dist_tolerance parameter controls the tolerance to which a point is considered to lie on the plane or not (distance to the plane) @@ -870,8 +867,7 @@ def projectionpoints(self, pps): return [pp - np.dot(pp - self.p1, self.normal_vector) * self.normal_vector for pp in pps] def orthonormal_vectors(self): - """ - Returns a list of three orthogonal vectors, the two first being parallel to the plane and the + """Get a list of three orthogonal vectors, the two first being parallel to the plane and the third one is the normal vector of the plane Returns: diff --git a/pymatgen/analysis/chemenv/utils/graph_utils.py b/pymatgen/analysis/chemenv/utils/graph_utils.py index 38e44818e79..b6be2626767 100644 --- a/pymatgen/analysis/chemenv/utils/graph_utils.py +++ b/pymatgen/analysis/chemenv/utils/graph_utils.py @@ -131,8 +131,7 @@ def _c2index_isreverse(c1, c2): class SimpleGraphCycle(MSONable): - """ - Class used to describe a cycle in a simple graph (graph without multiple edges). + """Describe a cycle in a simple graph (graph without multiple edges). Note that the convention used here is the networkx convention for which simple graphs allow to have self-loops in a simple graph. @@ -467,7 +466,6 @@ def __eq__(self, other: object) -> bool: def get_all_elementary_cycles(graph): """ - Args: graph: """ diff --git a/pymatgen/analysis/chemenv/utils/math_utils.py b/pymatgen/analysis/chemenv/utils/math_utils.py index d2488c4981a..152c87202c1 100644 --- a/pymatgen/analysis/chemenv/utils/math_utils.py +++ b/pymatgen/analysis/chemenv/utils/math_utils.py @@ -98,7 +98,6 @@ def divisors(n): def get_center_of_arc(p1, p2, radius): """ - Args: p1: p2: @@ -118,7 +117,6 @@ def get_center_of_arc(p1, p2, radius): def get_linearly_independent_vectors(vectors_list): """ - Args: vectors_list: """ @@ -142,7 +140,6 @@ def get_linearly_independent_vectors(vectors_list): def scale_and_clamp(xx, edge0, edge1, clamp0, clamp1): """ - Args: xx: edge0: @@ -156,7 +153,6 @@ def scale_and_clamp(xx, edge0, edge1, clamp0, clamp1): # Step function based on the cumulative distribution function of the normal law def normal_cdf_step(xx, mean, scale): """ - Args: xx: mean: @@ -174,7 +170,6 @@ def normal_cdf_step(xx, mean, scale): def smoothstep(xx, edges=None, inverse=False): """ - Args: xx: edges: @@ -191,7 +186,6 @@ def smoothstep(xx, edges=None, inverse=False): def smootherstep(xx, edges=None, inverse=False): """ - Args: xx: edges: @@ -208,7 +202,6 @@ def smootherstep(xx, edges=None, inverse=False): def cosinus_step(xx, edges=None, inverse=False): """ - Args: xx: edges: @@ -225,7 +218,6 @@ def cosinus_step(xx, edges=None, inverse=False): def power3_step(xx, edges=None, inverse=False): """ - Args: xx: edges: @@ -236,7 +228,6 @@ def power3_step(xx, edges=None, inverse=False): def powern_parts_step(xx, edges=None, inverse=False, nn=2): """ - Args: xx: edges: @@ -280,7 +271,6 @@ def powern_parts_step(xx, edges=None, inverse=False, nn=2): def powern_decreasing(xx, edges=None, nn=2): """ - Args: xx: edges: @@ -295,7 +285,6 @@ def powern_decreasing(xx, edges=None, nn=2): def power2_decreasing_exp(xx, edges=None, alpha=1.0): """ - Args: xx: edges: @@ -315,7 +304,6 @@ def power2_decreasing_exp(xx, edges=None, alpha=1.0): def power2_tangent_decreasing(xx, edges=None, prefactor=None): """ - Args: xx: edges: @@ -331,7 +319,6 @@ def power2_tangent_decreasing(xx, edges=None, prefactor=None): def power2_inverse_decreasing(xx, edges=None, prefactor=None): """ - Args: xx: edges: @@ -347,7 +334,6 @@ def power2_inverse_decreasing(xx, edges=None, prefactor=None): def power2_inverse_power2_decreasing(xx, edges=None, prefactor=None): """ - Args: xx: edges: @@ -366,7 +352,6 @@ def power2_inverse_power2_decreasing(xx, edges=None, prefactor=None): def power2_inverse_powern_decreasing(xx, edges=None, prefactor=None, powern=2.0): """ - Args: xx: edges: diff --git a/pymatgen/analysis/chempot_diagram.py b/pymatgen/analysis/chempot_diagram.py index 7b579d3f43b..68bba6a76ae 100644 --- a/pymatgen/analysis/chempot_diagram.py +++ b/pymatgen/analysis/chempot_diagram.py @@ -88,7 +88,7 @@ def __init__( which are used to construct the border hyperplanes used in the HalfSpaceIntersection algorithm; these constrain the space over which the domains are calculated and also determine the size of the plotted diagram. Any elemental limits not specified are - covered in the default_min_limit argument. e.g., {Element("Li"): [-12.0, 0.0], ...} + covered in the default_min_limit argument. e.g. {Element("Li"): [-12.0, 0.0], ...} default_min_limit (float): Default minimum chemical potential limit (i.e., lower bound) for unspecified elements within the "limits" argument. formal_chempots (bool): Whether to plot the formal ('reference') chemical potentials @@ -235,8 +235,7 @@ def _get_border_hyperplanes(self) -> np.ndarray: return border_hyperplanes def _get_hyperplanes_and_entries(self) -> tuple[np.ndarray, list[PDEntry]]: - """ - Returns both the array of hyperplanes, as well as a list of the minimum + """Get both the array of hyperplanes, as well as a list of the minimum entries. """ data = np.array( @@ -414,8 +413,7 @@ def _get_new_limits_from_padding( @staticmethod def _get_2d_domain_lines(draw_domains) -> list[Scatter]: - """ - Returns a list of Scatter objects tracing the domain lines on a + """Get a list of Scatter objects tracing the domain lines on a 2-dimensional chemical potential diagram. """ x, y = [], [] @@ -436,8 +434,7 @@ def _get_2d_domain_lines(draw_domains) -> list[Scatter]: @staticmethod def _get_3d_domain_lines(domains: dict[str, list[Simplex] | None]) -> list[Scatter3d]: - """ - Returns a list of Scatter3d objects tracing the domain lines on a + """Get a list of Scatter3d objects tracing the domain lines on a 3-dimensional chemical potential diagram. """ x, y, z = [], [], [] @@ -463,8 +460,7 @@ def _get_3d_domain_lines(domains: dict[str, list[Simplex] | None]) -> list[Scatt def _get_3d_domain_simplexes_and_ann_loc( points_3d: np.ndarray, ) -> tuple[list[Simplex], np.ndarray]: - """ - Returns a list of Simplex objects and coordinates of annotation for one + """Get a list of Simplex objects and coordinates of annotation for one domain in a 3-d chemical potential diagram. Uses PCA to project domain into 2-dimensional space so that ConvexHull can be used to identify the bounding polygon. @@ -483,8 +479,7 @@ def _get_3d_formula_meshes( draw_domains: dict[str, np.ndarray], formula_colors: list[str] | None, ) -> list[Mesh3d]: - """ - Returns a list of Mesh3d objects for the domains specified by the + """Get a list of Mesh3d objects for the domains specified by the user (i.e., draw_domains). """ meshes = [] @@ -544,8 +539,7 @@ def _get_3d_formula_lines( def _get_min_entries_and_el_refs( entries: list[PDEntry], ) -> tuple[list[PDEntry], dict[Element, PDEntry]]: - """ - Returns a list of the minimum-energy entries at each composition and the + """Get a list of the minimum-energy entries at each composition and the entries corresponding to the elemental references. """ el_refs = {} diff --git a/pymatgen/analysis/diffraction/core.py b/pymatgen/analysis/diffraction/core.py index ce669187def..e384f6eef0b 100644 --- a/pymatgen/analysis/diffraction/core.py +++ b/pymatgen/analysis/diffraction/core.py @@ -81,8 +81,7 @@ def get_plot( with_labels=True, fontsize=16, ) -> plt.Axes: - """ - Returns the diffraction plot as a matplotlib Axes. + """Get the diffraction plot as a matplotlib Axes. Args: structure: Input structure diff --git a/pymatgen/analysis/diffraction/neutron.py b/pymatgen/analysis/diffraction/neutron.py index 6b2dc452429..694182dc960 100644 --- a/pymatgen/analysis/diffraction/neutron.py +++ b/pymatgen/analysis/diffraction/neutron.py @@ -47,8 +47,7 @@ class NDCalculator(AbstractDiffractionPatternCalculator): """ def __init__(self, wavelength=1.54184, symprec: float = 0, debye_waller_factors=None): - """ - Initializes the ND calculator with a given radiation. + """Initialize the ND calculator with a given radiation. Args: wavelength (float): The wavelength of neutron in angstroms. diff --git a/pymatgen/analysis/diffraction/tem.py b/pymatgen/analysis/diffraction/tem.py index d08eb83918c..75f487c3a34 100644 --- a/pymatgen/analysis/diffraction/tem.py +++ b/pymatgen/analysis/diffraction/tem.py @@ -88,8 +88,7 @@ def wavelength_rel(self) -> float: @staticmethod def generate_points(coord_left: int = -10, coord_right: int = 10) -> np.ndarray: - """ - Generates a bunch of 3D points that span a cube. + """Generate a bunch of 3D points that span a cube. Args: coord_left (int): The minimum coordinate value. @@ -107,7 +106,7 @@ def generate_points(coord_left: int = -10, coord_right: int = 10) -> np.ndarray: def zone_axis_filter( self, points: list[tuple[int, int, int]] | np.ndarray, laue_zone: int = 0 ) -> list[tuple[int, int, int]]: - """Filters out all points that exist within the specified Laue zone according to the zone axis rule. + """Filter out all points that exist within the specified Laue zone according to the zone axis rule. Args: points (np.ndarray): The list of points to be filtered. @@ -282,8 +281,7 @@ def get_pattern( scaled: bool | None = None, two_theta_range: tuple[float, float] | None = None, ) -> pd.DataFrame: - """ - Returns all relevant TEM DP info in a pandas dataframe. + """Get all relevant TEM DP info in a pandas dataframe. Args: structure (Structure): The input structure. @@ -380,8 +378,7 @@ def get_first_point(self, structure: Structure, points: list) -> dict[tuple[int, @staticmethod def get_interplanar_angle(structure: Structure, p1: tuple[int, int, int], p2: tuple[int, int, int]) -> float: - """ - Returns the interplanar angle (in degrees) between the normal of two crystal planes. + """Get the interplanar angle (in degrees) between the normal of two crystal planes. Formulas from International Tables for Crystallography Volume C pp. 2-9. Args: @@ -514,8 +511,7 @@ def get_positions(self, structure: Structure, points: list) -> dict[tuple[int, i return positions def tem_dots(self, structure: Structure, points) -> list: - """ - Generates all TEM_dot as named tuples that will appear on the 2D diffraction pattern. + """Generate all TEM_dot as named tuples that will appear on the 2D diffraction pattern. Args: structure (Structure): The input structure. @@ -539,8 +535,7 @@ def tem_dots(self, structure: Structure, points) -> list: return dots def get_plot_2d(self, structure: Structure) -> go.Figure: - """ - Generates the 2D diffraction pattern of the input structure. + """Generate the 2D diffraction pattern of the input structure. Args: structure (Structure): The input structure. @@ -617,8 +612,7 @@ def get_plot_2d(self, structure: Structure) -> go.Figure: return go.Figure(data=data, layout=layout) def get_plot_2d_concise(self, structure: Structure) -> go.Figure: - """ - Generates the concise 2D diffraction pattern of the input structure of a smaller size and without layout. + """Generate the concise 2D diffraction pattern of the input structure of a smaller size and without layout. Does not display. Args: diff --git a/pymatgen/analysis/diffraction/xrd.py b/pymatgen/analysis/diffraction/xrd.py index 5b0f6322aa7..8a15d24fc9c 100644 --- a/pymatgen/analysis/diffraction/xrd.py +++ b/pymatgen/analysis/diffraction/xrd.py @@ -98,8 +98,7 @@ class XRDCalculator(AbstractDiffractionPatternCalculator): AVAILABLE_RADIATION = tuple(WAVELENGTHS) def __init__(self, wavelength="CuKa", symprec: float = 0, debye_waller_factors=None): - """ - Initializes the XRD calculator with a given radiation. + """Initialize the XRD calculator with a given radiation. Args: wavelength (str/float): The wavelength can be specified as either a diff --git a/pymatgen/analysis/disorder.py b/pymatgen/analysis/disorder.py index 73bbb82dac2..a47221add8c 100644 --- a/pymatgen/analysis/disorder.py +++ b/pymatgen/analysis/disorder.py @@ -20,7 +20,7 @@ def get_warren_cowley_parameters(structure: Structure, r: float, dr: float) -> d dr: Shell width Returns: - Warren-Crowley parameters in the form of a dict, e.g., {(Element Mo, Element W): -1.0, ...} + Warren-Crowley parameters in the form of a dict, e.g. {(Element Mo, Element W): -1.0, ...} """ comp = structure.composition diff --git a/pymatgen/analysis/elasticity/elastic.py b/pymatgen/analysis/elasticity/elastic.py index 1465491ba64..4d86f57d40a 100644 --- a/pymatgen/analysis/elasticity/elastic.py +++ b/pymatgen/analysis/elasticity/elastic.py @@ -129,7 +129,7 @@ class ElasticTensor(NthOrderElasticTensor): """ This class extends Tensor to describe the 3x3x3x3 second-order elastic tensor, C_{ijkl}, with various methods for estimating other properties derived from the second - order elastic tensor (e. g. bulk modulus, shear modulus, Young's modulus, Poisson's ratio) + order elastic tensor (e.g. bulk modulus, shear modulus, Young's modulus, Poisson's ratio) in units of eV/A^3. """ @@ -151,8 +151,7 @@ def __new__(cls, input_array, tol: float = 1e-4) -> Self: @property def compliance_tensor(self): - """ - Returns the Voigt notation compliance tensor, which is the matrix + """The Voigt notation compliance tensor, which is the matrix inverse of the Voigt notation elastic tensor. """ s_voigt = np.linalg.inv(self.voigt) @@ -380,7 +379,7 @@ def agne_diffusive_thermalcond(self, structure: Structure) -> float: @raise_if_unphysical def debye_temperature(self, structure: Structure) -> float: - """Estimates the Debye temperature from longitudinal and transverse sound velocities. + """Estimate the Debye temperature from longitudinal and transverse sound velocities. Args: structure: pymatgen structure object @@ -426,8 +425,7 @@ def property_dict(self): def get_structure_property_dict( self, structure: Structure, include_base_props: bool = True, ignore_errors: bool = False ) -> dict[str, float | Structure | None]: - """ - Returns a dictionary of properties derived from the elastic tensor + """Get a dictionary of properties derived from the elastic tensor and an associated structure. Args: @@ -540,7 +538,7 @@ class ElasticTensorExpansion(TensorCollection): to an elastic tensor expansion, which can be used to calculate stress and energy density and inherits all of the list-based properties of TensorCollection - (e. g. symmetrization, voigt conversion, etc.). + (e.g. symmetrization, voigt conversion, etc.). """ def __init__(self, c_list: Sequence) -> None: @@ -556,8 +554,7 @@ def __init__(self, c_list: Sequence) -> None: @classmethod def from_diff_fit(cls, strains, stresses, eq_stress=None, tol: float = 1e-10, order=3) -> Self: - """ - Generates an elastic tensor expansion via the fitting function + """Generate an elastic tensor expansion via the fitting function defined below in diff_fit. """ c_list = diff_fit(strains, stresses, eq_stress, order, tol) @@ -757,8 +754,7 @@ def get_strain_from_stress(self, stress): return strain def get_effective_ecs(self, strain, order=2): - """ - Returns the effective elastic constants + """Get the effective elastic constants from the elastic tensor expansion. Args: @@ -980,7 +976,7 @@ def generate_pseudo(strain_states, order=3): Args: strain_states (6xN array like): a list of Voigt-notation strain-states, i. e. perturbed indices of the strain as a function of the smallest - strain e. g. (0, 1, 0, 0, 1, 0) + strain e.g. (0, 1, 0, 0, 1, 0) order (int): order of pseudo-inverse to calculate Returns: @@ -1019,9 +1015,9 @@ def get_symbol_list(rank, dim=6): by index transposition, i. e. C_1121 = C_1211 etc. Args: - dim (int): dimension of matrix/tensor, e. g. 6 for + dim (int): dimension of matrix/tensor, e.g. 6 for voigt notation and 3 for standard - rank (int): rank of tensor, e. g. 3 for third-order ECs + rank (int): rank of tensor, e.g. 3 for third-order ECs Returns: c_vec (array): array representing distinct indices diff --git a/pymatgen/analysis/elasticity/strain.py b/pymatgen/analysis/elasticity/strain.py index b76fbab86d1..9edaf989c42 100644 --- a/pymatgen/analysis/elasticity/strain.py +++ b/pymatgen/analysis/elasticity/strain.py @@ -218,8 +218,7 @@ def from_index_amount(cls, idx: tuple | int, amount: float) -> Self: raise ValueError("Index must either be 2-tuple or integer corresponding to full-tensor or Voigt index") def get_deformation_matrix(self, shape: Literal["upper", "lower", "symmetric"] = "upper"): - """ - Returns the deformation matrix. + """Get the deformation matrix. Args: shape ('upper' | 'lower' | 'symmetric'): method for determining deformation diff --git a/pymatgen/analysis/elasticity/stress.py b/pymatgen/analysis/elasticity/stress.py index 5fce24d4f5e..edc3c5d4982 100644 --- a/pymatgen/analysis/elasticity/stress.py +++ b/pymatgen/analysis/elasticity/stress.py @@ -48,8 +48,7 @@ def __new__(cls, stress_matrix) -> Self: @property def dev_principal_invariants(self): - """ - Returns the principal invariants of the deviatoric stress tensor, + """The principal invariants of the deviatoric stress tensor, which is calculated by finding the coefficients of the characteristic polynomial of the stress tensor minus the identity times the mean stress. diff --git a/pymatgen/analysis/energy_models.py b/pymatgen/analysis/energy_models.py index 0dafed86a02..03a32cabe17 100644 --- a/pymatgen/analysis/energy_models.py +++ b/pymatgen/analysis/energy_models.py @@ -52,8 +52,7 @@ class EwaldElectrostaticModel(EnergyModel): """Wrapper around EwaldSum to calculate the electrostatic energy.""" def __init__(self, real_space_cut=None, recip_space_cut=None, eta=None, acc_factor=8.0): - """ - Initializes the model. Args have the same definitions as in + """Initialize the model. Args have the same definitions as in pymatgen.analysis.ewald.EwaldSummation. Args: diff --git a/pymatgen/analysis/eos.py b/pymatgen/analysis/eos.py index a2b03a6cdcc..310d0e6b94e 100644 --- a/pymatgen/analysis/eos.py +++ b/pymatgen/analysis/eos.py @@ -124,25 +124,18 @@ def __call__(self, volume: float) -> float: return self.func(volume) @property - def e0(self): + def e0(self) -> float: """Returns the min energy.""" return self._params[0] @property - def b0(self): - """ - Returns the bulk modulus. - Note: the units for the bulk modulus: unit of energy/unit of volume^3. - """ + def b0(self) -> float: + """The bulk modulus in units of energy/unit of volume^3.""" return self._params[1] @property - def b0_GPa(self): - """ - Returns the bulk modulus in GPa. - Note: This assumes that the energy and volumes are in eV and Ang^3 - respectively. - """ + def b0_GPa(self) -> FloatWithUnit: + """The bulk modulus in GPa. This assumes the energy and volumes are in eV and Ang^3.""" return FloatWithUnit(self.b0, "eV ang^-3").to("GPa") @property @@ -157,12 +150,7 @@ def v0(self): @property def results(self): - """ - Returns a summary dict. - - Returns: - dict - """ + """A summary dict.""" return {"e0": self.e0, "b0": self.b0, "b1": self.b1, "v0": self.v0} def plot(self, width=8, height=None, ax: plt.Axes = None, dpi=None, **kwargs): diff --git a/pymatgen/analysis/ewald.py b/pymatgen/analysis/ewald.py index d3aa686a24b..a0e2c9d9da6 100644 --- a/pymatgen/analysis/ewald.py +++ b/pymatgen/analysis/ewald.py @@ -67,8 +67,7 @@ def __init__( w=1 / 2**0.5, compute_forces=False, ): - """ - Initializes and calculates the Ewald sum. Default convergence + """Initialize and calculate the Ewald sum. Default convergence parameters have been specified, but you can override them if you wish. Args: @@ -196,8 +195,7 @@ def reciprocal_space_energy(self): @property def reciprocal_space_energy_matrix(self): - """ - The reciprocal space energy matrix. Each matrix element (i, j) + """The reciprocal space energy matrix. Each matrix element (i, j) corresponds to the interaction energy between site i and site j in reciprocal space. """ @@ -216,8 +214,7 @@ def real_space_energy(self): @property def real_space_energy_matrix(self): - """ - The real space energy matrix. Each matrix element (i, j) corresponds to + """The real space energy matrix. Each matrix element (i, j) corresponds to the interaction energy between site i and site j in real space. """ if not self._initialized: @@ -235,8 +232,7 @@ def point_energy(self): @property def point_energy_matrix(self): - """ - The point space matrix. A diagonal matrix with the point terms for each + """The point space matrix. A diagonal matrix with the point terms for each site in the diagonal elements. """ if not self._initialized: @@ -254,8 +250,7 @@ def total_energy(self): @property def total_energy_matrix(self): - """ - The total energy matrix. Each matrix element (i, j) corresponds to the + """The total energy matrix. Each matrix element (i, j) corresponds to the total interaction energy between site i and site j. Note that this does not include the charged-cell energy, which is only important @@ -272,10 +267,7 @@ def total_energy_matrix(self): @property def forces(self): - """ - The forces on each site as a Nx3 matrix. Each row corresponds to a - site. - """ + """The forces on each site as a Nx3 matrix. Each row corresponds to a site.""" if not self._initialized: self._calc_ewald_terms() self._initialized = True @@ -621,7 +613,7 @@ def best_case(self, matrix, m_list, indices_left): elapsed_time = datetime.utcnow() - self._start_time speedup_parameter = elapsed_time.total_seconds() / 1800 avg_int = np.sum(interaction_matrix, axis=None) - avg_frac = np.average(np.outer(1 - fractions, 1 - fractions)) + avg_frac = np.mean(np.outer(1 - fractions, 1 - fractions)) average_correction = avg_int * avg_frac interaction_correction = average_correction * speedup_parameter + interaction_correction * ( @@ -632,8 +624,7 @@ def best_case(self, matrix, m_list, indices_left): @classmethod def get_next_index(cls, matrix, manipulation, indices_left): - """ - Returns an index that should have the most negative effect on the + """Get an index that should have the most negative effect on the matrix sum. """ diff --git a/pymatgen/analysis/ferroelectricity/polarization.py b/pymatgen/analysis/ferroelectricity/polarization.py index 9e79ba1cbdf..2942e2b0b05 100644 --- a/pymatgen/analysis/ferroelectricity/polarization.py +++ b/pymatgen/analysis/ferroelectricity/polarization.py @@ -315,8 +315,7 @@ def get_same_branch_polarization_data(self, convert_to_muC_per_cm2=True, all_in_ return np.array(adjust_pol) def get_lattice_quanta(self, convert_to_muC_per_cm2=True, all_in_polar=True): - """ - Returns the dipole / polarization quanta along a, b, and c for + """Get the dipole / polarization quanta along a, b, and c for all structures. """ lattices = [s.lattice for s in self.structures] diff --git a/pymatgen/analysis/graphs.py b/pymatgen/analysis/graphs.py index 5cd1334ddfb..d06f2e59e6a 100644 --- a/pymatgen/analysis/graphs.py +++ b/pymatgen/analysis/graphs.py @@ -752,8 +752,7 @@ def map_indices(grp: Molecule) -> dict[int, int]: ) def get_connected_sites(self, n: int, jimage: tuple[int, int, int] = (0, 0, 0)) -> list[ConnectedSite]: - """ - Returns a named tuple of neighbors of site n: + """Get a named tuple of neighbors of site n: periodic_site, jimage, index, weight. Index is the index of the corresponding site in the original structure, weight can be @@ -805,8 +804,7 @@ def get_connected_sites(self, n: int, jimage: tuple[int, int, int] = (0, 0, 0)) return _connected_sites def get_coordination_of_site(self, n: int) -> int: - """ - Returns the number of neighbors of site n. In graph terms, + """Get the number of neighbors of site n. In graph terms, simply returns degree of node corresponding to site n. Args: @@ -1483,7 +1481,7 @@ def get_subgraphs_as_molecules(self, use_weights: bool = False) -> list[Molecule list of unique Molecules in Structure """ # creating a supercell is an easy way to extract - # molecules (and not, e.g., layers of a 2D crystal) + # molecules (and not, e.g. layers of a 2D crystal) # without adding extra logic if getattr(self, "_supercell_sg", None) is None: self._supercell_sg = supercell_sg = self * (3, 3, 3) @@ -2442,8 +2440,7 @@ def find_rings(self, including=None) -> list[list[tuple[int, int]]]: return cycles_edges def get_connected_sites(self, n): - """ - Returns a named tuple of neighbors of site n: + """Get a named tuple of neighbors of site n: periodic_site, jimage, index, weight. Index is the index of the corresponding site in the original structure, weight can be @@ -2484,8 +2481,7 @@ def get_connected_sites(self, n): return connected_sites def get_coordination_of_site(self, n) -> int: - """ - Returns the number of neighbors of site n. + """Get the number of neighbors of site n. In graph terms, simply returns degree of node corresponding to site n. diff --git a/pymatgen/analysis/interface_reactions.py b/pymatgen/analysis/interface_reactions.py index 22a21d1fb59..e3d093082c9 100644 --- a/pymatgen/analysis/interface_reactions.py +++ b/pymatgen/analysis/interface_reactions.py @@ -207,8 +207,7 @@ def plot(self, backend: Literal["plotly", "matplotlib"] = "plotly") -> Figure | return fig def get_dataframe(self) -> DataFrame: - """ - Returns a pandas DataFrame representation of the data produced by the + """Get a pandas DataFrame representation of the data produced by the get_kinks() method. """ rxns = [ @@ -224,8 +223,7 @@ def get_dataframe(self) -> DataFrame: return DataFrame(rxns) def get_critical_original_kink_ratio(self): - """ - Returns a list of molar mixing ratio for each kink between ORIGINAL + """Get a list of molar mixing ratio for each kink between ORIGINAL (instead of processed) reactant compositions. This is the same list as mixing ratio obtained from get_kinks method if self.norm = False. @@ -243,8 +241,7 @@ def get_critical_original_kink_ratio(self): return ratios def _get_original_composition_ratio(self, reaction): - """ - Returns the molar mixing ratio between the reactants with ORIGINAL ( + """Get the molar mixing ratio between the reactants with ORIGINAL ( instead of processed) compositions for a reaction. Args: @@ -287,8 +284,7 @@ def _get_reactants(self, x: float) -> list[Composition]: return reactants def _get_reaction(self, x: float) -> Reaction: - """ - Generates balanced reaction at mixing ratio x : (1-x) for + """Generate balanced reaction at mixing ratio x : (1-x) for self.comp1 : self.comp2. Args: @@ -488,7 +484,7 @@ def _convert(x: float, factor1: float, factor2: float): x: Mixing ratio x in comp1 - comp2 tie line, a float between 0 and 1. factor1: Compositional ratio between composition c1 and - processed composition comp1. E.g., factor for + processed composition comp1. e.g. factor for Composition('SiO2') and Composition('O') is 2.0. factor2: Compositional ratio between composition c2 and processed composition comp2. @@ -508,7 +504,7 @@ def _reverse_convert(x: float, factor1: float, factor2: float): x: Mixing ratio x in c1 - c2 tie line, a float between 0 and 1. factor1: Compositional ratio between composition c1 and - processed composition comp1. E.g., factor for + processed composition comp1. e.g. factor for Composition('SiO2') and Composition('O') is 2. factor2: Compositional ratio between composition c2 and processed composition comp2. @@ -567,12 +563,11 @@ def get_chempot_correction(cls, element: str, temp: float, pres: float): @property def labels(self): - """ - Returns a dictionary containing kink information: + """A dictionary containing kink information: {index: 'x= mixing_ratio energy= reaction_energy reaction_equation'}. - E.g., {1: 'x= 0 energy = 0 Mn -> Mn', - 2: 'x= 0.5 energy = -15 O2 + Mn -> MnO2', - 3: 'x= 1 energy = 0 O2 -> O2'}. + e.g. {1: 'x= 0 energy = 0 Mn -> Mn', + 2: 'x= 0.5 energy = -15 O2 + Mn -> MnO2', + 3: 'x= 1 energy = 0 O2 -> O2'}. """ return { j: f"x= {x:.4} energy in eV/atom = {energy:.4} {reaction}" for j, x, energy, reaction, _ in self.get_kinks() @@ -590,7 +585,7 @@ def minimum(self): @property def products(self): - """List of formulas of potential products. E.g., ['Li','O2','Mn'].""" + """List of formulas of potential products. e.g. ['Li','O2','Mn'].""" products = set() for _, _, _, react, _ in self.get_kinks(): products = products | {key.reduced_formula for key in react.products} @@ -666,8 +661,7 @@ def __init__( self.e2 = self.pd.get_hull_energy(self.comp2) def get_no_mixing_energy(self): - """ - Generates the opposite number of energy above grand potential + """Generate the opposite number of energy above grand potential convex hull for both reactants. Returns: diff --git a/pymatgen/analysis/interfaces/substrate_analyzer.py b/pymatgen/analysis/interfaces/substrate_analyzer.py index 8064f71653f..49d816861e9 100644 --- a/pymatgen/analysis/interfaces/substrate_analyzer.py +++ b/pymatgen/analysis/interfaces/substrate_analyzer.py @@ -94,8 +94,7 @@ class SubstrateAnalyzer(ZSLGenerator): """ def __init__(self, film_max_miller=1, substrate_max_miller=1, **kwargs): - """ - Initializes the substrate analyzer + """Initialize the substrate analyzer Args: zslgen (ZSLGenerator): Defaults to a ZSLGenerator with standard @@ -113,8 +112,7 @@ def __init__(self, film_max_miller=1, substrate_max_miller=1, **kwargs): def generate_surface_vectors( self, film: Structure, substrate: Structure, film_millers: ArrayLike, substrate_millers: ArrayLike ): - """ - Generates the film/substrate slab combinations for a set of given + """Generate the film/substrate slab combinations for a set of given miller indices. Args: diff --git a/pymatgen/analysis/interfaces/zsl.py b/pymatgen/analysis/interfaces/zsl.py index 79867a3d34a..65cebe57058 100644 --- a/pymatgen/analysis/interfaces/zsl.py +++ b/pymatgen/analysis/interfaces/zsl.py @@ -109,8 +109,7 @@ def __init__( self.bidirectional = bidirectional def generate_sl_transformation_sets(self, film_area, substrate_area): - """ - Generates transformation sets for film/substrate pair given the + """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 lattices with a maximum area diff --git a/pymatgen/analysis/local_env.py b/pymatgen/analysis/local_env.py index b9d02b99842..22cf5913937 100644 --- a/pymatgen/analysis/local_env.py +++ b/pymatgen/analysis/local_env.py @@ -163,7 +163,7 @@ def nearest_key(sorted_vals: list[int], skey: int) -> int: return radii def _get_valences(self): - """Computes ionic valences of elements for all sites in the structure.""" + """Compute ionic valences of elements for all sites in the structure.""" try: bv = BVAnalyzer() self._structure = bv.get_oxi_state_decorated_structure(self._structure) @@ -2359,20 +2359,14 @@ def __init__(self, types, parameters=None, cutoff=-10.0) -> None: self._cos_n_p: dict[int, list[float]] = {} @property - def num_ops(self): - """ - Returns: - int: the number of different order parameters that are targeted to be calculated. - """ + def num_ops(self) -> int: + """Number of different order parameters that are targeted to be calculated.""" return len(self._types) @property def last_nneigh(self): - """ - Returns: - int: the number of neighbors encountered during the most - recent order parameter calculation. A value of -1 indicates - that no such calculation has yet been performed for this instance. + """Number of neighbors encountered during the most recent order parameter calculation. + A value of -1 indicates that no such calculation has yet been performed for this instance. """ return len(self._last_nneigh) @@ -2769,8 +2763,7 @@ def get_type(self, index): return self._types[index] def get_parameters(self, index): - """ - Returns list of floats that represents + """Get list of floats that represents the parameters associated with calculation of the order parameter that was defined at the index provided. @@ -4155,7 +4148,7 @@ def _get_radius(site): if oxi in el.ionic_radii: return el.ionic_radii[oxi] - # e.g., oxi = 2.667, average together 2+ and 3+ radii + # e.g. oxi = 2.667, average together 2+ and 3+ radii if math.floor(oxi) in el.ionic_radii and math.ceil(oxi) in el.ionic_radii: oxi_low = el.ionic_radii[math.floor(oxi)] oxi_high = el.ionic_radii[math.ceil(oxi)] diff --git a/pymatgen/analysis/magnetism/heisenberg.py b/pymatgen/analysis/magnetism/heisenberg.py index 701031be38a..7b6f089de10 100644 --- a/pymatgen/analysis/magnetism/heisenberg.py +++ b/pymatgen/analysis/magnetism/heisenberg.py @@ -101,8 +101,7 @@ def __init__(self, ordered_structures, energies, cutoff=0, tol: float = 0.02): @staticmethod def _get_graphs(cutoff, ordered_structures): - """ - Generate graph representations of magnetic structures with nearest + """Generate graph representations of magnetic structures with nearest neighbor bonds. Right now this only works for MinimumDistanceNN. Args: diff --git a/pymatgen/analysis/molecule_structure_comparator.py b/pymatgen/analysis/molecule_structure_comparator.py index 9e89308c370..c77bb2babc5 100644 --- a/pymatgen/analysis/molecule_structure_comparator.py +++ b/pymatgen/analysis/molecule_structure_comparator.py @@ -138,8 +138,7 @@ class CovalentRadius: class MoleculeStructureComparator(MSONable): - """ - Class to check whether the connection tables of the two molecules are the + """Check whether the connection tables of the two molecules are the same. The atom in the two molecule must be paired accordingly. """ diff --git a/pymatgen/analysis/nmr.py b/pymatgen/analysis/nmr.py index 53a0169bbb0..a98515e57a2 100644 --- a/pymatgen/analysis/nmr.py +++ b/pymatgen/analysis/nmr.py @@ -65,8 +65,7 @@ def __new__(cls, cs_matrix, vscale=None) -> Self | None: # type: ignore[misc] @property def principal_axis_system(self): - """ - Returns a chemical shielding tensor aligned to the principle axis system + """A chemical shielding tensor aligned to the principle axis system so that only the 3 diagonal components are non-zero. """ return ChemicalShielding(np.diag(np.sort(np.linalg.eigvals(self.symmetrized)))) @@ -155,9 +154,8 @@ def __new__(cls, efg_matrix, vscale=None) -> Self | None: # type: ignore[misc] @property def principal_axis_system(self): - """ - Returns a electric field gradient tensor aligned to the principle axis system so that only the 3 diagonal - components are non-zero. + """An electric field gradient tensor aligned to the principle axis system so that + only the 3 diagonal components are non-zero. """ return ElectricFieldGradient(np.diag(np.sort(np.linalg.eigvals(self)))) @@ -181,10 +179,7 @@ def V_zz(self): @property def asymmetry(self): - """ - Asymmetry of the electric field tensor defined as: - (V_yy - V_xx)/V_zz. - """ + """Asymmetry of the electric field tensor defined as (V_yy - V_xx)/V_zz.""" diags = np.diag(self.principal_axis_system) V = sorted(diags, key=np.abs) return np.abs((V[1] - V[0]) / V[2]) diff --git a/pymatgen/analysis/phase_diagram.py b/pymatgen/analysis/phase_diagram.py index ea3bda3a61b..75d029b0b08 100644 --- a/pymatgen/analysis/phase_diagram.py +++ b/pymatgen/analysis/phase_diagram.py @@ -90,10 +90,7 @@ def __repr__(self): @property def energy(self) -> float: - """ - Returns: - the energy of the entry. - """ + """The entry's energy.""" return self._energy def as_dict(self): @@ -115,10 +112,10 @@ def from_dict(cls, dct: dict) -> Self: PDEntry """ return cls( - Composition(dct["composition"]), - dct["energy"], - dct.get("name"), - dct.get("attribute"), + composition=Composition(dct["composition"]), + energy=dct["energy"], + name=dct.get("name"), + attribute=dct.get("attribute"), ) @@ -169,11 +166,8 @@ def chemical_energy(self): return sum(self._composition[el] * pot for el, pot in self.chempots.items()) @property - def energy(self): - """ - Returns: - The grand potential energy. - """ + def energy(self) -> float: + """Grand potential energy.""" return self._energy - self.chemical_energy def __repr__(self): @@ -514,10 +508,7 @@ def pd_coords(self, comp: Composition) -> np.ndarray: @property def all_entries_hulldata(self): - """ - Returns: - The actual ndarray used to construct the convex hull. - """ + """The ndarray used to construct the convex hull.""" data = [ [e.composition.get_atomic_fraction(el) for el in self.elements] + [e.energy_per_atom] for e in self.all_entries @@ -574,8 +565,7 @@ def get_reference_energy_per_atom(self, comp: Composition) -> float: return self.get_reference_energy(comp) / comp.num_atoms def get_form_energy(self, entry: PDEntry) -> float: - """ - Returns the formation energy for an entry (NOT normalized) from the + """Get the formation energy for an entry (NOT normalized) from the elemental references. Args: @@ -588,8 +578,7 @@ def get_form_energy(self, entry: PDEntry) -> float: return entry.energy - self.get_reference_energy(comp) def get_form_energy_per_atom(self, entry: PDEntry) -> float: - """ - Returns the formation energy per atom for an entry from the + """Get the formation energy per atom for an entry from the elemental references. Args: @@ -661,8 +650,7 @@ def _get_facet_chempots(self, facet): return dict(zip(self.elements, chempots)) def _get_simplex_intersections(self, c1, c2): - """ - Returns coordinates of the intersection of the tie line between two compositions + """Get coordinates of the intersection of the tie line between two compositions and the simplexes of the PhaseDiagram. Args: @@ -1145,12 +1133,11 @@ def get_element_profile(self, element, comp, comp_tol=1e-5): def get_chempot_range_map( self, elements: Sequence[Element], referenced: bool = True, joggle: bool = True ) -> dict[Element, list[Simplex]]: - """ - Returns a chemical potential range map for each stable entry. + """Get a chemical potential range map for each stable entry. Args: elements: Sequence of elements to be considered as independent variables. - E.g., if you want to show the stability ranges + e.g. if you want to show the stability ranges of all Li-Co-O phases with respect to mu_Li and mu_O, you will supply [Element("Li"), Element("O")] referenced: If True, gives the results with a reference being the @@ -1198,8 +1185,7 @@ def get_chempot_range_map( return chempot_ranges def getmu_vertices_stability_phase(self, target_comp, dep_elt, tol_en=1e-2): - """ - Returns a set of chemical potentials corresponding to the vertices of + """Get a set of chemical potentials corresponding to the vertices of the simplex in the chemical potential phase diagram. The simplex is built using all elements in the target_composition except dep_elt. @@ -1257,8 +1243,7 @@ def getmu_vertices_stability_phase(self, target_comp, dep_elt, tol_en=1e-2): return None def get_chempot_range_stability_phase(self, target_comp, open_elt): - """ - Returns a set of chemical potentials corresponding to the max and min + """Get a set of chemical potentials corresponding to the max and min chemical potential of the open element for a given composition. It is quite common to have for instance a ternary oxide (e.g., ABO3) for which you want to know what are the A and B chemical potential leading @@ -1476,8 +1461,7 @@ class CompoundPhaseDiagram(PhaseDiagram): amount_tol = 1e-5 def __init__(self, entries, terminal_compositions, normalize_terminal_compositions=True): - """ - Initializes a CompoundPhaseDiagram. + """Initialize a CompoundPhaseDiagram. Args: entries ([PDEntry]): Sequence of input entries. For example, @@ -1883,7 +1867,7 @@ def _get_pd_patch_for_space(self, space: frozenset[Element]) -> tuple[frozenset[ class ReactionDiagram: """ - Analyzes the possible reactions between a pair of compounds, e.g., + Analyzes the possible reactions between a pair of compounds, e.g. an electrolyte and an electrode. """ @@ -1892,12 +1876,12 @@ def __init__(self, entry1, entry2, all_entries, tol: float = 1e-4, float_fmt="%. Args: entry1 (ComputedEntry): Entry for 1st component. Note that corrections, if any, must already be pre-applied. This is to - give flexibility for different kinds of corrections, e.g., + give flexibility for different kinds of corrections, e.g. if a particular entry is fitted to an experimental data (such as EC molecule). entry2 (ComputedEntry): Entry for 2nd component. Note that corrections must already be pre-applied. This is to - give flexibility for different kinds of corrections, e.g., + give flexibility for different kinds of corrections, e.g. if a particular entry is fitted to an experimental data (such as EC molecule). all_entries ([ComputedEntry]): All other entries to be @@ -2377,7 +2361,7 @@ class (pymatgen.analysis.chempot_diagram). Args: elements: Sequence of elements to be considered as independent - variables. E.g., if you want to show the stability ranges of + variables. e.g. if you want to show the stability ranges of all Li-Co-O phases w.r.t. to uLi and uO, you will supply [Element("Li"), Element("O")] referenced: if True, gives the results with a reference being the @@ -2386,8 +2370,7 @@ class (pymatgen.analysis.chempot_diagram). self.get_chempot_range_map_plot(elements, referenced=referenced).show() def get_chempot_range_map_plot(self, elements, referenced=True): - """ - Returns a plot of the chemical potential range _map. Currently works + """Get a plot of the chemical potential range _map. Currently works only for 3-component PDs. Note: this functionality is now included in the ChemicalPotentialDiagram @@ -2395,7 +2378,7 @@ class (pymatgen.analysis.chempot_diagram). Args: elements: Sequence of elements to be considered as independent - variables. E.g., if you want to show the stability ranges of + variables. e.g. if you want to show the stability ranges of all Li-Co-O phases w.r.t. to uLi and uO, you will supply [Element("Li"), Element("O")] referenced: if True, gives the results with a reference being the @@ -3749,12 +3732,12 @@ def uniquelines(q): used for converting convex hull facets into line pairs of coordinates. Args: - q: A 2-dim sequence, where each row represents a facet. E.g., + q: A 2-dim sequence, where each row represents a facet. e.g. [[1,2,3],[3,6,7],...] Returns: setoflines: - A set of tuple of lines. E.g., ((1,2), (1,3), (2,3), ....) + A set of tuple of lines. e.g. ((1,2), (1,3), (2,3), ....) """ return {tuple(sorted(line)) for facets in q for line in itertools.combinations(facets, 2)} diff --git a/pymatgen/analysis/piezo_sensitivity.py b/pymatgen/analysis/piezo_sensitivity.py index ffa3f3aee3f..11b666a06be 100644 --- a/pymatgen/analysis/piezo_sensitivity.py +++ b/pymatgen/analysis/piezo_sensitivity.py @@ -52,8 +52,7 @@ def __init__(self, structure: Structure, bec, pointops, tol: float = 1e-3): warnings.warn("Input born effective charge tensor does not satisfy charge neutrality") def get_BEC_operations(self, eigtol=1e-5, opstol=1e-3): - """ - Returns the symmetry operations which maps the tensors + """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 index 1 to site index 2]]. @@ -110,8 +109,7 @@ def get_BEC_operations(self, eigtol=1e-5, opstol=1e-3): return BEC_operations def get_rand_BEC(self, max_charge=1): - """ - Generate a random born effective charge tensor which obeys a structure's + """Generate a random born effective charge tensor which obeys a structure's symmetry and the acoustic sum rule. Args: @@ -187,8 +185,7 @@ def __init__(self, structure: Structure, ist, pointops, tol: float = 1e-3): warnings.warn("Input internal strain tensor does not satisfy standard symmetries") def get_IST_operations(self, opstol=1e-3): - """ - Returns the symmetry operations which maps the tensors + """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 index 1 to site index 2]]. @@ -224,8 +221,7 @@ def get_IST_operations(self, opstol=1e-3): self.IST_operations = IST_operations def get_rand_IST(self, max_force=1): - """ - Generate a random internal strain tensor which obeys a structure's + """Generate a random internal strain tensor which obeys a structure's symmetry and the acoustic sum rule. Args: @@ -277,8 +273,7 @@ def __init__(self, structure: Structure, fcm, pointops, sharedops, tol: float = self.FCM_operations = None def get_FCM_operations(self, eigtol=1e-5, opstol=1e-5): - """ - Returns the symmetry operations which maps the tensors + """Get the symmetry operations which maps the tensors belonging to equivalent sites onto each other in the form [site index 1a, site index 1b, site index 2a, site index 2b, [Symmops mapping from site index 1a, 1b to site index 2a, 2b]]. @@ -351,8 +346,7 @@ def get_FCM_operations(self, eigtol=1e-5, opstol=1e-5): return FCM_operations def get_unstable_FCM(self, max_force=1): - """ - Generate an unsymmetrized force constant matrix. + """Generate an unsymmetrized force constant matrix. Args: max_charge (float): maximum born effective charge value @@ -410,8 +404,7 @@ def get_unstable_FCM(self, max_force=1): return D def get_symmetrized_FCM(self, unsymmetrized_fcm, max_force=1): - """ - Generate a symmetrized force constant matrix from an unsymmetrized matrix. + """Generate a symmetrized force constant matrix from an unsymmetrized matrix. Args: unsymmetrized_fcm (numpy array): unsymmetrized force constant matrix @@ -467,8 +460,7 @@ def get_symmetrized_FCM(self, unsymmetrized_fcm, max_force=1): return unsymmetrized_fcm def get_stable_FCM(self, fcm, fcmasum=10): - """ - Generate a symmetrized force constant matrix that obeys the objects symmetry + """Generate a symmetrized force constant matrix that obeys the objects symmetry constraints, has no unstable modes and also obeys the acoustic sum rule through an iterative procedure. @@ -516,8 +508,7 @@ def get_stable_FCM(self, fcm, fcmasum=10): # acoustic sum def get_asum_FCM(self, fcm: np.ndarray, numiter: int = 15): - """ - Generate a symmetrized force constant matrix that obeys the objects symmetry + """Generate a symmetrized force constant matrix that obeys the objects symmetry constraints and obeys the acoustic sum rule through an iterative procedure. Args: @@ -606,8 +597,7 @@ def get_asum_FCM(self, fcm: np.ndarray, numiter: int = 15): @requires(Phonopy, "phonopy not installed!") def get_rand_FCM(self, asum=15, force=10): - """ - Generate a symmetrized force constant matrix from an unsymmetrized matrix + """Generate a symmetrized force constant matrix from an unsymmetrized matrix that has no unstable modes and also obeys the acoustic sum rule through an iterative procedure. diff --git a/pymatgen/analysis/pourbaix_diagram.py b/pymatgen/analysis/pourbaix_diagram.py index 4253f4cc496..f6f0c8928a3 100644 --- a/pymatgen/analysis/pourbaix_diagram.py +++ b/pymatgen/analysis/pourbaix_diagram.py @@ -107,22 +107,22 @@ def __init__(self, entry, entry_id=None, concentration=1e-6): @property def npH(self): - """Get the number of H.""" + """The number of H.""" return self.entry.composition.get("H", 0) - 2 * self.entry.composition.get("O", 0) @property def nH2O(self): - """Get the number of H2O.""" + """The number of H2O.""" return self.entry.composition.get("O", 0) @property def nPhi(self): - """Get the number of electrons.""" + """The number of electrons.""" return self.npH - self.charge @property def name(self): - """Get the name for entry.""" + """The entry's name.""" if self.phase_type == "Solid": return f"{self.entry.reduced_formula}(s)" @@ -170,10 +170,8 @@ def get_element_fraction(self, element): @property def normalized_energy(self): - """ - Returns: - energy normalized by number of non H or O atoms, e. g. - for Zn2O6, energy / 2 or for AgTe3(OH)3, energy / 4. + """Energy normalized by number of non H or O atoms, e.g. + for Zn2O6, energy / 2 or for AgTe3(OH)3, energy / 4. """ return self.energy * self.normalization_factor @@ -192,16 +190,14 @@ def normalized_energy_at_conditions(self, pH, V): @property def conc_term(self): - """ - Returns the concentration contribution to the free energy, - and should only be present when there are ions in the entry. + """The concentration contribution to the free energy. Should only be present + when there are ions in the entry. """ return PREFAC * np.log10(self.concentration) # TODO: not sure if these are strictly necessary with refactor def as_dict(self): - """ - Returns dict which contains Pourbaix Entry data. + """Get dict which contains Pourbaix Entry data. Note that the pH, voltage, H2O factors are always calculated when constructing a PourbaixEntry object. """ @@ -262,8 +258,7 @@ class MultiEntry(PourbaixEntry): """ def __init__(self, entry_list, weights=None): - """ - Initializes a MultiEntry. + """Initialize a MultiEntry. Args: entry_list ([PourbaixEntry]): List of component PourbaixEntries @@ -343,7 +338,7 @@ def __init__(self, ion: Ion, energy: float, name: str | None = None, attribute=N energy: Energy for composition. name: Optional parameter to name the entry. Defaults to the chemical formula. - attribute: Optional attribute of the entry, e.g., band gap. + attribute: Optional attribute of the entry, e.g. band gap. """ self.ion = ion # Auto-assign name @@ -513,8 +508,7 @@ def _convert_entries_to_points(self, pourbaix_entries): return vecs def _get_hull_in_nph_nphi_space(self, entries) -> tuple[list[PourbaixEntry], list[Simplex]]: - """ - Generates convex hull of Pourbaix diagram entries in composition, + """Generate convex hull of Pourbaix diagram entries in composition, npH, and nphi space. This enables filtering of multi-entries such that only compositionally stable combinations of entries are included. @@ -571,8 +565,7 @@ def _get_hull_in_nph_nphi_space(self, entries) -> tuple[list[PourbaixEntry], lis return min_entries, valid_facets def _preprocess_pourbaix_entries(self, entries, nproc=None): - """ - Generates multi-entries for Pourbaix diagram. + """Generate multi-entries for Pourbaix diagram. Args: entries ([PourbaixEntry]): list of PourbaixEntries to preprocess @@ -705,8 +698,7 @@ def process_multientry(entry_list, prod_comp, coeff_threshold=1e-4): @staticmethod def get_pourbaix_domains(pourbaix_entries, limits=None): - """ - Returns a set of Pourbaix stable domains (i. e. polygons) in + """Get a set of Pourbaix stable domains (i. e. polygons) in pH-V space from a list of pourbaix_entries. This function works by using scipy's HalfspaceIntersection @@ -752,7 +744,7 @@ def get_pourbaix_domains(pourbaix_entries, limits=None): [0, 0, -1, 2 * g_max], ] hs_hyperplanes = np.vstack([hyperplanes, border_hyperplanes]) - interior_point = [*np.average(limits, axis=1).tolist(), g_max] + interior_point = [*np.mean(limits, axis=1).tolist(), g_max] hs_int = HalfspaceIntersection(hs_hyperplanes, np.array(interior_point)) # organize the boundary points by entry @@ -771,7 +763,7 @@ def get_pourbaix_domains(pourbaix_entries, limits=None): points = np.array(points)[:, :2] # Initial sort to ensure consistency points = points[np.lexsort(np.transpose(points))] - center = np.average(points, axis=0) + center = np.mean(points, axis=0) points_centered = points - center # Sort points by cross product of centered points, @@ -979,7 +971,7 @@ def get_pourbaix_plot( ax.plot(V0_line[0], V0_line[1], "k-.", linewidth=lw) for entry, vertices in self._pbx._stable_domain_vertices.items(): - center = np.average(vertices, axis=0) + center = np.mean(vertices, axis=0) x, y = np.transpose(np.vstack([vertices, vertices[0]])) ax.plot(x, y, "k-", linewidth=lw) @@ -1049,8 +1041,7 @@ def plot_entry_stability( return ax def domain_vertices(self, entry): - """ - Returns the vertices of the Pourbaix domain. + """Get the vertices of the Pourbaix domain. Args: entry: Entry for which domain vertices are desired diff --git a/pymatgen/analysis/quasirrho.py b/pymatgen/analysis/quasirrho.py index 5498e5fda5b..b7be8bb64c1 100644 --- a/pymatgen/analysis/quasirrho.py +++ b/pymatgen/analysis/quasirrho.py @@ -68,17 +68,16 @@ def get_avg_mom_inertia(mol): inertia_tensor[ii, jj] += -wt * c[ii] * c[jj] inertia_tensor[jj, ii] += -wt * c[jj] * c[ii] - # amuangs^2 to kg m^2 + # atomic mass unit * angstrom^2 to kg m^2 inertia_eigen_vals = np.linalg.eig(inertia_tensor)[0] * amu_to_kg * 1e-20 - iav = np.average(inertia_eigen_vals) + iav = np.mean(inertia_eigen_vals) return iav, inertia_eigen_vals class QuasiRRHO: - """ - Class to calculate thermochemistry using Grimme's Quasi-RRHO approximation. + """Calculate thermochemistry using Grimme's Quasi-RRHO approximation. All outputs are in atomic units, e.g. energy outputs are in Hartrees. Citation: Grimme, S. Chemistry - A European Journal 18, 9955-9964 (2012). diff --git a/pymatgen/analysis/reaction_calculator.py b/pymatgen/analysis/reaction_calculator.py index 48d541510fe..4fd9e17cce5 100644 --- a/pymatgen/analysis/reaction_calculator.py +++ b/pymatgen/analysis/reaction_calculator.py @@ -149,8 +149,7 @@ def normalize_to_element(self, element: Species | Element, factor: float = 1) -> self._coeffs = [c * scale_factor for c in coeffs] def get_el_amount(self, element: Element | Species) -> float: - """ - Returns the amount of the element in the reaction. + """Get the amount of the element in the reaction. Args: element (Element/Species): Element in the reaction @@ -236,9 +235,7 @@ def _str_from_comp(cls, coeffs, compositions, reduce=False) -> tuple[str, float] return cls._str_from_formulas(r_coeffs, r_formulas), factor def as_entry(self, energies) -> ComputedEntry: - """ - Returns a ComputedEntry representation of the reaction. - """ + """Get a ComputedEntry representation of the reaction.""" relevant_comp = [comp * abs(coeff) for coeff, comp in zip(self._coeffs, self._all_comp)] comp: Composition = sum(relevant_comp, Composition()) # type: ignore[assignment] @@ -273,8 +270,7 @@ def from_dict(cls, dct: dict) -> Self: @classmethod def from_str(cls, rxn_str: str) -> Self: - """ - Generates a balanced reaction from a string. The reaction must + """Generate a balanced reaction from a string. The reaction must already be balanced. Args: @@ -306,7 +302,7 @@ class Reaction(BalancedReaction): def __init__(self, reactants: list[Composition], products: list[Composition]) -> None: """ Reactants and products to be specified as list of - pymatgen.core.structure.Composition. e.g., [comp1, comp2]. + pymatgen.core.structure.Composition. e.g. [comp1, comp2]. Args: reactants ([Composition]): List of reactants. diff --git a/pymatgen/analysis/structure_analyzer.py b/pymatgen/analysis/structure_analyzer.py index 2ae34f84df3..a520db2694d 100644 --- a/pymatgen/analysis/structure_analyzer.py +++ b/pymatgen/analysis/structure_analyzer.py @@ -190,8 +190,7 @@ def __init__(self, initial_structure: Structure, final_structure: Structure) -> self.final = final_structure def get_percentage_volume_change(self) -> float: - """ - Returns the percentage volume change. + """Get the percentage volume change. Returns: float: Volume change in percent. 0.055 means a 5.5% increase. @@ -199,11 +198,10 @@ def get_percentage_volume_change(self) -> float: return self.final.volume / self.initial.volume - 1 def get_percentage_lattice_parameter_changes(self) -> dict[str, float]: - """ - Returns the percentage lattice parameter changes. + """Get the percentage lattice parameter changes. Returns: - dict[str, float]: Percent changes in lattice parameter, e.g., + dict[str, float]: Percent changes in lattice parameter, e.g. {'a': 0.012, 'b': 0.021, 'c': -0.031} implies a change of 1.2%, 2.1% and -3.1% in the a, b and c lattice parameters respectively. """ @@ -212,8 +210,7 @@ def get_percentage_lattice_parameter_changes(self) -> dict[str, float]: return {length: getattr(final_latt, length) / getattr(initial_latt, length) - 1 for length in ["a", "b", "c"]} def get_percentage_bond_dist_changes(self, max_radius: float = 3.0) -> dict[int, dict[int, float]]: - """ - Returns the percentage bond distance changes for each site up to a + """Get the percentage bond distance changes for each site up to a maximum radius for nearest neighbors. Args: @@ -262,15 +259,10 @@ def __init__(self, structure: Structure, cutoff=10): @property def connectivity_array(self): - """ - Provides connectivity array. - - Returns: - connectivity: An array of shape [atom_i, atom_j, image_j]. atom_i is - the index of the atom in the input structure. Since the second - atom can be outside of the unit cell, it must be described - by both an atom index and an image index. Array data is the - solid angle of polygon between atom_i and image_j of atom_j + """The connectivity array of shape [atom_i, atom_j, image_j]. atom_i is the index of the + atom in the input structure. Since the second atom can be outside of the unit cell, it + must be described by both an atom index and an image index. Array data is the solid + angle of polygon between atom_i and image_j of atom_j. """ # shape = [site, axis] cart_coords = np.array(self.structure.cart_coords) @@ -307,15 +299,13 @@ def connectivity_array(self): @property def max_connectivity(self): - """ - Returns the 2d array [site_i, site_j] that represents the maximum connectivity of + """The 2d array [site_i, site_j] that represents the maximum connectivity of site i to any periodic image of site j. """ return np.max(self.connectivity_array, axis=2) def get_connections(self): - """ - Returns a list of site pairs that are Voronoi Neighbors, along + """Get a list of site pairs that are Voronoi Neighbors, along with their real-space distances. """ con = [] diff --git a/pymatgen/analysis/structure_matcher.py b/pymatgen/analysis/structure_matcher.py index 079ea0b927d..8b3b6609d67 100644 --- a/pymatgen/analysis/structure_matcher.py +++ b/pymatgen/analysis/structure_matcher.py @@ -282,11 +282,9 @@ def get_hash(self, composition): class StructureMatcher(MSONable): - """ - Class to match structures by similarity. + """Match structures by similarity. Algorithm: - 1. Given two structures: s1 and s2 2. Optional: Reduce to primitive cells. 3. If the number of sites do not match, return False @@ -364,7 +362,7 @@ def __init__( SpeciesComparator, which implies rigid species mapping, i.e., Fe2+ only matches Fe2+ and not Fe3+. - Other comparators are provided, e.g., ElementComparator which + Other comparators are provided, e.g. ElementComparator which matches only the elements and not the species. The reason why a comparator object is used instead of @@ -377,7 +375,7 @@ def __init__( present in both structures. ignored_species (list): A list of ions to be ignored in matching. Useful for matching structures that have similar frameworks - except for certain ions, e.g., Li-ion intercalation frameworks. + except for certain ions, e.g. Li-ion intercalation frameworks. This is more useful than allow_subset because it allows better control over what species are ignored in the matching. """ @@ -393,8 +391,7 @@ def __init__( self._ignored_species = ignored_species def _get_supercell_size(self, s1, s2): - """ - Returns the supercell size, and whether the supercell should be applied to s1. + """Get the supercell size, and whether the supercell should be applied to s1. If fu == 1, s1_supercell is returned as true, to avoid ambiguity. """ if self._supercell_size == "num_sites": @@ -484,8 +481,7 @@ def sc_generator(s1, s2): @classmethod def _cmp_fstruct(cls, s1, s2, frac_tol, mask): - """ - Returns true if a matching exists between s2 and s2 + """Get true if a matching exists between s2 and s2 under frac_tol. s2 should be a subset of s1. """ if len(s2) > len(s1): @@ -524,15 +520,14 @@ def _cart_dists(cls, s1, s2, avg_lattice, mask, normalization, lll_frac_tol=None lin = LinearAssignment(d_2) sol = lin.solution short_vecs = vecs[np.arange(len(sol)), sol] - translation = np.average(short_vecs, axis=0) + translation = np.mean(short_vecs, axis=0) f_translation = avg_lattice.get_fractional_coords(translation) new_d2 = np.sum((short_vecs - translation) ** 2, axis=-1) return new_d2**0.5 * normalization, f_translation, sol def _get_mask(self, struct1, struct2, fu, s1_supercell): - """ - Returns mask for matching struct2 to struct1. If struct1 has sites + """Get mask for matching struct2 to struct1. If struct1 has sites a b c, and fu = 2, assumes supercells of struct2 will be ordered aabbcc (rather than abcabc). @@ -959,7 +954,7 @@ def _get_reduced_structure(cls, struct: Structure, primitive_cell: bool = True, def get_rms_anonymous(self, struct1, struct2): """ Performs an anonymous fitting, which allows distinct species in one - structure to map to another. E.g., to compare if the Li2O and Na2O + structure to map to another. e.g. to compare if the Li2O and Na2O structures are similar. Args: @@ -985,7 +980,7 @@ def get_rms_anonymous(self, struct1, struct2): def get_best_electronegativity_anonymous_mapping(self, struct1: Structure, struct2: Structure) -> dict | None: """ Performs an anonymous fitting, which allows distinct species in one - structure to map to another. E.g., to compare if the Li2O and Na2O + structure to map to another. e.g. to compare if the Li2O and Na2O structures are similar. If multiple substitutions are within tolerance this will return the one which minimizes the difference in electronegativity between the matches species. @@ -1048,7 +1043,7 @@ def fit_anonymous( ) -> bool: """ Performs an anonymous fitting, which allows distinct species in one structure to map - to another. E.g., to compare if the Li2O and Na2O structures are similar. + to another. e.g. to compare if the Li2O and Na2O structures are similar. Args: struct1 (Structure): 1st structure @@ -1068,8 +1063,7 @@ def fit_anonymous( return bool(matches) def get_supercell_matrix(self, supercell, struct) -> np.ndarray | None: - """ - Returns the matrix for transforming struct to supercell. This + """Get the matrix for transforming struct to supercell. This can be used for very distorted 'supercells' where the primitive cell is impossible to find. """ @@ -1088,8 +1082,7 @@ def get_supercell_matrix(self, supercell, struct) -> np.ndarray | None: return match[2] def get_transformation(self, struct1, struct2): - """ - Returns the supercell transformation, fractional translation vector, + """Get the supercell transformation, fractional translation vector, and a mapping to transform struct2 to be similar to struct1. Args: diff --git a/pymatgen/analysis/structure_prediction/substitution_probability.py b/pymatgen/analysis/structure_prediction/substitution_probability.py index c5b6239d66c..5ae92fe2279 100644 --- a/pymatgen/analysis/structure_prediction/substitution_probability.py +++ b/pymatgen/analysis/structure_prediction/substitution_probability.py @@ -250,8 +250,7 @@ def _recurse(output_prob, output_species): return output def composition_prediction(self, composition, to_this_composition=True): - """ - Returns charged balanced substitutions from a starting or ending + """Get charged balanced substitutions from a starting or ending composition. Args: diff --git a/pymatgen/analysis/structure_prediction/substitutor.py b/pymatgen/analysis/structure_prediction/substitutor.py index fa7892b28e2..36efa6b1b6d 100644 --- a/pymatgen/analysis/structure_prediction/substitutor.py +++ b/pymatgen/analysis/structure_prediction/substitutor.py @@ -65,8 +65,7 @@ def __init__(self, threshold=1e-3, symprec: float = 0.1, **kwargs): self._symprec = symprec def get_allowed_species(self): - """ - Returns the species in the domain of the probability function + """Get the species in the domain of the probability function any other specie will not work. """ return self._sp.species @@ -96,7 +95,7 @@ def pred_from_structures( Args: target_species: a list of species with oxidation states - e.g., [Species('Li+'), Species('Ni2+'), Species('O-2')] + e.g. [Species('Li+'), Species('Ni2+'), Species('O-2')] structures_list: list of dictionary of the form {'structure': Structure object, 'id': some id where it comes from} diff --git a/pymatgen/analysis/surface_analysis.py b/pymatgen/analysis/surface_analysis.py index b8852702834..6a06ec83572 100644 --- a/pymatgen/analysis/surface_analysis.py +++ b/pymatgen/analysis/surface_analysis.py @@ -149,8 +149,7 @@ def as_dict(self): return dct def gibbs_binding_energy(self, eads=False): - """ - Returns the adsorption energy or Gibbs binding energy of an adsorbate on a surface. + """Get the adsorption energy or Gibbs binding energy of an adsorbate on a surface. Args: eads (bool): Whether to calculate the adsorption energy @@ -232,20 +231,14 @@ def surface_energy(self, ucell_entry, ref_entries=None): @property def get_unit_primitive_area(self): - """ - Returns the surface area of the adsorbed system per - unit area of the primitive slab system. - """ + """The surface area of the adsorbed system per unit area of the primitive slab system.""" A_ads = self.surface_area A_clean = self.clean_entry.surface_area return A_ads / A_clean @property def get_monolayer(self): - """ - Returns the primitive unit surface area density of the - adsorbate. - """ + """The primitive unit surface area density of the adsorbate.""" unit_a = self.get_unit_primitive_area n_surfs = self.Nsurfs_ads_in_slab n_ads = self.Nads_in_slab @@ -449,8 +442,7 @@ def get_stable_entry_at_u( no_doped=False, no_clean=False, ) -> tuple[SlabEntry, float]: - """ - Returns the entry corresponding to the most stable slab for a particular + """Get the entry corresponding to the most stable slab for a particular facet at a specific chempot. We assume that surface energy is constant so all free variables must be set with delu_dict, otherwise they are assumed to be equal to delu_default. @@ -1159,7 +1151,7 @@ def surface_chempot_range_map( Args: elements (list): Sequence of elements to be considered as independent - variables. E.g., if you want to show the stability ranges of + variables. e.g. if you want to show the stability ranges of all Li-Co-O phases w.r.t. to duLi and duO, you will supply [Element("Li"), Element("O")] miller_index ([h, k, l]): Miller index of the surface we are interested in @@ -1347,8 +1339,7 @@ class WorkFunctionAnalyzer: """ def __init__(self, structure: Structure, locpot_along_c, efermi, shift=0, blength=3.5): - """ - Initializes the WorkFunctionAnalyzer class. + """Initialize the WorkFunctionAnalyzer class. Args: structure (Structure): Structure object modelling the surface @@ -1416,8 +1407,7 @@ def __init__(self, structure: Structure, locpot_along_c, efermi, shift=0, blengt self.ave_locpot = (self.vacuum_locpot - min(self.locpot_along_c)) / 2 def get_locpot_along_slab_plot(self, label_energies=True, plt=None, label_fontsize=10): - """ - Returns a plot of the local potential (eV) vs the + """Get a plot of the local potential (eV) vs the position along the c axis of the slab model (Ang). Args: @@ -1574,8 +1564,7 @@ def is_converged(self, min_points_frac=0.015, tol: float = 0.0025): @classmethod def from_files(cls, poscar_filename, locpot_filename, outcar_filename, shift=0, blength=3.5) -> Self: - """ - Initializes a WorkFunctionAnalyzer from POSCAR, LOCPOT, and OUTCAR files. + """Initialize a WorkFunctionAnalyzer from POSCAR, LOCPOT, and OUTCAR files. Args: poscar_filename (str): The path to the POSCAR file. @@ -1728,8 +1717,7 @@ def wulff_gform_and_r( @staticmethod def bulk_gform(bulk_entry): - """ - Returns the formation energy of the bulk. + """Get the formation energy of the bulk. Args: bulk_entry (ComputedStructureEntry): Entry of the corresponding bulk. @@ -1779,8 +1767,7 @@ def plot_one_stability_map( normalize=False, scale_per_atom=False, ): - """ - Returns the plot of the formation energy of a particle against its + """Get the plot of the formation energy of a particle against its effect radius. Args: @@ -1846,8 +1833,7 @@ def plot_all_stability_map( normalize=False, scale_per_atom=False, ): - """ - Returns the plot of the formation energy of a particles + """Get the plot of the formation energy of a particles of different polymorphs against its effect radius. Args: diff --git a/pymatgen/analysis/thermochemistry.py b/pymatgen/analysis/thermochemistry.py index 5c4ec46b721..a5d4acdea6a 100644 --- a/pymatgen/analysis/thermochemistry.py +++ b/pymatgen/analysis/thermochemistry.py @@ -45,7 +45,7 @@ def __init__( Fe2O3. phaseinfo (str): Denoting the phase. For example, "solid", "liquid", "gas" or "tetragonal". - formula (str): A proper string formula, e.g., Fe2O3 + formula (str): A proper string formula, e.g. Fe2O3 value (float): The value of the data. ref (str): A reference, if any, for the data. method (str): The method by which the data was determined, diff --git a/pymatgen/analysis/transition_state.py b/pymatgen/analysis/transition_state.py index cf083daf97b..817e5199e1d 100644 --- a/pymatgen/analysis/transition_state.py +++ b/pymatgen/analysis/transition_state.py @@ -30,8 +30,7 @@ class NEBAnalysis(MSONable): """An NEBAnalysis class.""" def __init__(self, r, energies, forces, structures, spline_options=None): - """ - Initializes an NEBAnalysis from the cumulative root mean squared distances + """Initialize an NEBAnalysis from the cumulative root mean squared distances between structures, the energies, the forces, the structures and the interpolation_order for the analysis. @@ -86,9 +85,8 @@ def setup_spline(self, spline_options=None): @classmethod def from_outcars(cls, outcars, structures, **kwargs) -> Self: - """ - Initializes an NEBAnalysis from Outcar and Structure objects. Use - the static constructors, e.g., from_dir instead if you + """Initialize an NEBAnalysis from Outcar and Structure objects. Use + the static constructors, e.g. from_dir instead if you prefer to have these automatically generated from a directory of NEB calculations. @@ -99,7 +97,7 @@ def from_outcars(cls, outcars, structures, **kwargs) -> Self: coordinate. Must be same length as outcar. interpolation_order (int): Order of polynomial to use to interpolate between images. Same format as order parameter in - scipy.interplotate.PiecewisePolynomial. + scipy.interpolate.PiecewisePolynomial. """ if len(outcars) != len(structures): raise ValueError("# of Outcars must be same as # of Structures") @@ -116,8 +114,7 @@ def from_outcars(cls, outcars, structures, **kwargs) -> Self: prev = st rms_dist = np.cumsum(rms_dist) - energies = [] - forces = [] + energies, forces = [], [] for idx, outcar in enumerate(outcars): outcar.read_neb() energies.append(outcar.data["energy"]) @@ -130,8 +127,7 @@ def from_outcars(cls, outcars, structures, **kwargs) -> Self: return cls(r=rms_dist, energies=energies, forces=forces, structures=structures, **kwargs) def get_extrema(self, normalize_rxn_coordinate=True): - """ - Returns the positions of the extrema along the MEP. Both local + """Get the positions of the extrema along the MEP. Both local minimums and maximums are returned. Args: @@ -192,8 +188,7 @@ def get_plot(self, normalize_rxn_coordinate: bool = True, label_barrier: bool = @classmethod def from_dir(cls, root_dir, relaxation_dirs=None, **kwargs) -> Self: - """ - Initializes a NEBAnalysis object from a directory of a NEB run. + """Initialize a NEBAnalysis object from a directory of a NEB run. Note that OUTCARs must be present in all image directories. For the terminal OUTCARs from relaxation calculations, you can specify the locations using relaxation_dir. If these are not specified, the code @@ -204,7 +199,7 @@ def from_dir(cls, root_dir, relaxation_dirs=None, **kwargs) -> Self: non-terminal points, the CONTCAR is read to obtain structures. For terminal points, the POSCAR is used. The image directories are assumed to be the only directories that can be resolved to integers. - E.g., "00", "01", "02", "03", "04", "05", "06". The minimum + e.g. "00", "01", "02", "03", "04", "05", "06". The minimum sub-directory structure that can be parsed is of the following form ( a 5-image example is shown): @@ -293,7 +288,7 @@ def combine_neb_plots(neb_analyses, arranged_neb_analyses=False, reverse_plot=Fa smallest-energy difference. If all end points have very close energies, it's likely to result in an inaccurate connection. Manually arrange neb_analyses if the combined plot is not as expected compared with all individual plots. - E.g., if there are two NEBAnalysis objects to combine, arrange in such a + e.g. if there are two NEBAnalysis objects to combine, arrange in such a way that the end-point energy of the first NEBAnalysis object is the start-point energy of the second NEBAnalysis object. Note that the barrier labeled in y-axis in the combined plot might be diff --git a/pymatgen/analysis/wulff.py b/pymatgen/analysis/wulff.py index a13d3667aea..6a1b537e320 100644 --- a/pymatgen/analysis/wulff.py +++ b/pymatgen/analysis/wulff.py @@ -708,17 +708,15 @@ def total_surface_energy(self) -> float: @property def tot_corner_sites(self): - """ - Returns the number of vertices in the convex hull. - Useful for identifying catalytically active sites. + """The number of vertices in the convex hull. + Useful for identifying catalytically active sites. """ return len(self.wulff_convex.vertices) @property def tot_edges(self): - """ - Returns the number of edges in the convex hull. - Useful for identifying catalytically active sites. + """The number of edges in the convex hull. + Useful for identifying catalytically active sites. """ all_edges = [] for facet in self.facets: diff --git a/pymatgen/apps/battery/battery_abc.py b/pymatgen/apps/battery/battery_abc.py index 56ca216f278..b6d3df592fb 100644 --- a/pymatgen/apps/battery/battery_abc.py +++ b/pymatgen/apps/battery/battery_abc.py @@ -1,6 +1,6 @@ """This module defines the abstract base classes for battery-related classes. Regardless of the kind of electrode, conversion or insertion, there are many -common definitions and properties, e.g., average voltage, capacity, etc. which +common definitions and properties, e.g. average voltage, capacity, etc. which can be defined in a general way. The Abc for battery classes implements some of these common definitions to allow sharing of common logic between them. """ diff --git a/pymatgen/apps/battery/conversion_battery.py b/pymatgen/apps/battery/conversion_battery.py index 05d6d055f12..9de6f9fc330 100644 --- a/pymatgen/apps/battery/conversion_battery.py +++ b/pymatgen/apps/battery/conversion_battery.py @@ -56,7 +56,7 @@ def from_composition_and_pd( composition and a phase diagram. Args: - comp: Starting composition for ConversionElectrode, e.g., + comp: Starting composition for ConversionElectrode, e.g. Composition("FeF3") pd: A PhaseDiagram of the relevant system (e.g., Li-Fe-F) working_ion_symbol: Element symbol of working ion. Defaults to Li. @@ -113,10 +113,10 @@ def from_composition_and_entries( composition and all entries in a chemical system. Args: - comp: Starting composition for ConversionElectrode, e.g., + comp: Starting composition for ConversionElectrode, e.g. Composition("FeF3") entries_in_chemsys: Sequence containing all entries in a - chemical system. E.g., all Li-Fe-F containing entries. + chemical system. e.g. all Li-Fe-F containing entries. working_ion_symbol: Element symbol of working ion. Defaults to Li. allow_unstable: If True, allow any composition to be used as the starting point of a conversion voltage curve, this is useful diff --git a/pymatgen/apps/battery/insertion_battery.py b/pymatgen/apps/battery/insertion_battery.py index 74e97031726..da13336e85a 100644 --- a/pymatgen/apps/battery/insertion_battery.py +++ b/pymatgen/apps/battery/insertion_battery.py @@ -383,7 +383,7 @@ def as_dict_legacy(self): @dataclass class InsertionVoltagePair(AbstractVoltagePair): - """Defines an Insertion Voltage Pair.""" + """A voltage pair for an insertion battery, e.g. LiFePO4 -> FePO4.""" entry_charge: ComputedEntry entry_discharge: ComputedEntry diff --git a/pymatgen/cli/pmg.py b/pymatgen/cli/pmg.py index aedb8d5676e..b239f36e4fe 100755 --- a/pymatgen/cli/pmg.py +++ b/pymatgen/cli/pmg.py @@ -90,7 +90,7 @@ def main(): parser_config = subparsers.add_parser( "config", - help="Tools for configuring pymatgen, e.g., potcar setup, modifying .pmgrc.yaml configuration file.", + help="Tools for configuring pymatgen, e.g. potcar setup, modifying .pmgrc.yaml configuration file.", ) groups = parser_config.add_mutually_exclusive_group(required=True) groups.add_argument( @@ -122,7 +122,7 @@ def main(): "--add", dest="var_spec", nargs="+", - help="Variables to add in the form of space separated key value pairs. E.g., PMG_VASP_PSP_DIR ~/PSPs", + help="Variables to add in the form of space separated key value pairs. e.g. PMG_VASP_PSP_DIR ~/PSPs", ) groups.add_argument( @@ -265,7 +265,7 @@ def main(): "--xrd", dest="xrd_structure_file", metavar="structure_file", - help="Generate XRD plots from any supported structure file, e.g., CIF, POSCAR, vasprun.xml, etc.", + help="Generate XRD plots from any supported structure file, e.g. CIF, POSCAR, vasprun.xml, etc.", ) parser_plot.add_argument( @@ -282,7 +282,7 @@ def main(): dest="element", type=str, nargs=1, - help="List of elements to plot as comma-separated values e.g., Fe,Mn", + help="List of elements to plot as comma-separated values e.g. Fe,Mn", ) parser_plot.add_argument( "-o", @@ -300,7 +300,7 @@ def main(): type=str, nargs=1, help="Comma-separated list of indices to plot " - "charge integration, e.g., 1,2,3,4. If not " + "charge integration, e.g. 1,2,3,4. If not " "provided, the code will plot the chgint " "for all symmetrically distinct atoms " "detected.", @@ -372,7 +372,7 @@ def main(): dest="localenv", nargs="+", help="Local environment analysis. Provide bonds in the format of" - "Center Species-Ligand Species=max_dist, e.g., H-O=0.5.", + "Center Species-Ligand Species=max_dist, e.g. H-O=0.5.", ) parser_structure.set_defaults(func=analyze_structures) @@ -385,7 +385,7 @@ def main(): dest="exclude_bonding", type=str, nargs=1, - help="List of elements to exclude from bonding analysis. E.g., Li,Na", + help="List of elements to exclude from bonding analysis. e.g. Li,Na", ) parser_view.set_defaults(func=parse_view) diff --git a/pymatgen/command_line/bader_caller.py b/pymatgen/command_line/bader_caller.py index 70da1146cba..ec0202421a4 100644 --- a/pymatgen/command_line/bader_caller.py +++ b/pymatgen/command_line/bader_caller.py @@ -422,7 +422,7 @@ def get_decorated_structure(self, property_name: str, average: bool = False) -> @property def summary(self) -> dict[str, Any]: - """Dict summary of key analysis, e.g., atomic volume, charge, etc.""" + """Dict summary of key analysis, e.g. atomic volume, charge, etc.""" summary = { "min_dist": [d["min_dist"] for d in self.data], "charge": [d["charge"] for d in self.data], diff --git a/pymatgen/command_line/gulp_caller.py b/pymatgen/command_line/gulp_caller.py index 1ae23bfe14b..7e2b0e2dfc8 100644 --- a/pymatgen/command_line/gulp_caller.py +++ b/pymatgen/command_line/gulp_caller.py @@ -338,7 +338,7 @@ def specie_potential_lines(structure, potential, **kwargs): @staticmethod def library_line(file_name): - """Specifies GULP library file to read species and potential parameters. + """Specify GULP library file to read species and potential parameters. If using library don't specify species and potential in the input file and vice versa. Make sure the elements of structure are in the library file. diff --git a/pymatgen/command_line/mcsqs_caller.py b/pymatgen/command_line/mcsqs_caller.py index ffad4b32341..9083ac98663 100644 --- a/pymatgen/command_line/mcsqs_caller.py +++ b/pymatgen/command_line/mcsqs_caller.py @@ -50,9 +50,9 @@ def run_mcsqs( clusters (dict): Dictionary of cluster interactions with entries in the form number of atoms: cutoff in angstroms scaling (int or list): Scaling factor to determine supercell. Two options are possible: - a. (preferred) Scales number of atoms, e.g., for a structure with 8 atoms, + a. (preferred) Scales number of atoms, e.g. for a structure with 8 atoms, scaling=4 would lead to a 32 atom supercell - b. A sequence of three scaling factors, e.g., [2, 1, 1], which + b. A sequence of three scaling factors, e.g. [2, 1, 1], which specifies that the supercell should have dimensions 2a x b x c Defaults to 1. search_time (float): Time spent looking for the ideal SQS in minutes (default: 60) diff --git a/pymatgen/core/bonds.py b/pymatgen/core/bonds.py index 294c2a1593e..9adb208c92c 100644 --- a/pymatgen/core/bonds.py +++ b/pymatgen/core/bonds.py @@ -31,7 +31,7 @@ def _load_bond_length_data(): class CovalentBond: - """Defines a covalent bond between two sites.""" + """A covalent bond between two sites.""" def __init__(self, site1: Site, site2: Site) -> None: """Initialize a covalent bond between two sites. diff --git a/pymatgen/core/composition.py b/pymatgen/core/composition.py index 6b669e8d2ff..c66955c938a 100644 --- a/pymatgen/core/composition.py +++ b/pymatgen/core/composition.py @@ -48,7 +48,7 @@ class Composition(collections.abc.Hashable, collections.abc.Mapping, MSONable, S __getitem__ is overridden to return 0 when an element is not found. (somewhat like a defaultdict, except it is immutable). - Also adds more convenience methods relevant to compositions, e.g., + Also adds more convenience methods relevant to compositions, e.g. get_fraction. It should also be noted that many Composition related functionality takes @@ -105,14 +105,14 @@ def __init__(self, *args, strict: bool = False, **kwargs) -> None: 1. A dict of either {Element/Species: amount}, {string symbol:amount}, or {atomic number:amount} or any mixture - of these. E.g., {Element("Li"): 2, Element("O"): 1}, + of these. e.g. {Element("Li"): 2, Element("O"): 1}, {"Li":2, "O":1}, {3: 2, 8: 1} all result in a Li2O composition. - 2. Keyword arg initialization, similar to a dict, e.g., + 2. Keyword arg initialization, similar to a dict, e.g. Composition(Li = 2, O = 1) In addition, the Composition constructor also allows a single - string as an input formula. E.g., Composition("Li2O"). + string as an input formula. e.g. Composition("Li2O"). Args: *args: Any number of 2-tuples as key-value pairs. @@ -173,7 +173,13 @@ def __contains__(self, key) -> bool: raise TypeError(f"Invalid {key=} for Composition") from exc def __eq__(self, other: object) -> bool: - """Defines == for Compositions.""" + """Composition equality. We consider compositions equal if they have the + same elements and the amounts are within Composition.amount_tolerance + of each other. + + Args: + other: Composition to compare to. + """ if not isinstance(other, (Composition, dict)): return NotImplemented @@ -186,8 +192,12 @@ def __eq__(self, other: object) -> bool: return all(abs(amt - other[el]) <= Composition.amount_tolerance for el, amt in self.items()) def __ge__(self, other: object) -> bool: - """Defines >= for Compositions. Should ONLY be used for defining a sort - order (the behavior is probably not what you'd expect). + """Composition greater than or equal to. We consider compositions A >= B + if all elements in B are in A and the amount of each element in A is + greater than or equal to the amount of the element in B within + Composition.amount_tolerance. + + Should ONLY be used for defining a sort order (the behavior is probably not what you'd expect). """ if not isinstance(other, Composition): return NotImplemented @@ -195,6 +205,7 @@ def __ge__(self, other: object) -> bool: for el in sorted(set(self.elements + other.elements)): if other[el] - self[el] >= Composition.amount_tolerance: return False + # TODO @janosh 2024-04-29: is this a bug? why would we return True early? if self[el] - other[el] >= Composition.amount_tolerance: return True return True @@ -290,7 +301,7 @@ def copy(self) -> Composition: @property def formula(self) -> str: """Returns a formula string, with elements sorted by electronegativity, - e.g., Li4 Fe4 P4 O16. + e.g. Li4 Fe4 P4 O16. """ sym_amt = self.get_el_amt_dict() syms = sorted(sym_amt, key=lambda sym: get_el_sp(sym).X) @@ -300,7 +311,7 @@ def formula(self) -> str: @property def alphabetical_formula(self) -> str: """Returns a formula string, with elements sorted by alphabetically - e.g., Fe4 Li4 O16 P4. + e.g. Fe4 Li4 O16 P4. """ return " ".join(sorted(self.formula.split())) @@ -733,7 +744,7 @@ def oxi_state_guesses( """Check if the composition is charge-balanced and returns back all charge-balanced oxidation state combinations. Composition must have integer values. Note that more num_atoms in the composition gives - more degrees of freedom. e.g., if possible oxidation states of + more degrees of freedom. e.g. if possible oxidation states of element X are [2,4] and Y are [-3], then XY is not charge balanced but X2Y2 is. Results are returned from most to least probable based on ICSD statistics. Use max_sites to improve performance if needed. diff --git a/pymatgen/core/interface.py b/pymatgen/core/interface.py index 63ef288740d..e86fb4b5bf6 100644 --- a/pymatgen/core/interface.py +++ b/pymatgen/core/interface.py @@ -88,9 +88,9 @@ def __init__( i. A sequence of element / species specified either as string symbols, e.g. ["Li", "Fe2+", "P", ...] or atomic numbers, - e.g., (3, 56, ...) or actual Element or Species objects. + e.g. (3, 56, ...) or actual Element or Species objects. - ii. List of dict of elements/species and occupancies, e.g., + ii. List of dict of elements/species and occupancies, e.g. [{"Fe" : 0.5, "Mn":0.5}, ...]. This allows the setup of disordered structures. coords (Nx3 array): list of fractional/cartesian coordinates for each species. @@ -287,8 +287,7 @@ def as_dict(self): @classmethod def from_dict(cls, dct: dict) -> GrainBoundary: # type: ignore[override] - """ - Generates a GrainBoundary object from a dictionary created by as_dict(). + """Generate a GrainBoundary object from a dictionary created by as_dict(). Args: dct: dict @@ -2359,16 +2358,16 @@ def __init__( lattice (Lattice/3x3 array): The lattice, either as a pymatgen.core.Lattice or simply as any 2D array. Each row should correspond to a lattice - vector. E.g., [[10,0,0], [20,10,0], [0,0,30]] specifies a + vector. e.g. [[10,0,0], [20,10,0], [0,0,30]] specifies a lattice with lattice vectors [10,0,0], [20,10,0] and [0,0,30]. species ([Species]): Sequence of species on each site. Can take in flexible input, including: i. A sequence of element / species specified either as string symbols, e.g. ["Li", "Fe2+", "P", ...] or atomic numbers, - e.g., (3, 56, ...) or actual Element or Species objects. + e.g. (3, 56, ...) or actual Element or Species objects. - ii. List of dict of elements/species and occupancies, e.g., + ii. List of dict of elements/species and occupancies, e.g. [{"Fe" : 0.5, "Mn":0.5}, ...]. This allows the setup of disordered structures. coords (Nx3 array): list of fractional/cartesian coordinates of @@ -2379,7 +2378,7 @@ def __init__( coords_are_cartesian (bool): Set to True if you are providing coordinates in Cartesian coordinates. Defaults to False. site_properties (dict): Properties associated with the sites as a - dict of sequences, e.g., {"magmom":[5,5,5,5]}. The sequences + dict of sequences, e.g. {"magmom":[5,5,5,5]}. The sequences have to be the same length as the atomic species and fractional_coords. Defaults to None for no properties. in_plane_offset: fractional shift in plane for the film with respect @@ -2511,7 +2510,7 @@ def get_sorted_structure(self, key=None, reverse=False) -> Structure: return struct_copy def get_shifts_based_on_adsorbate_sites(self, tolerance: float = 0.1) -> list[tuple[float, float]]: - """Computes possible in-plane shifts based on an adsorbate site algorithm. + """Compute possible in-plane shifts based on an adsorbate site algorithm. Args: tolerance: tolerance for "uniqueness" for shifts in Cartesian unit @@ -2707,7 +2706,7 @@ def from_slabs( # Shift coords to center if center_slab: - coords = np.add(coords, [0, 0, 0.5 - np.average(coords[:, 2])]) + coords = np.add(coords, [0, 0, 0.5 - np.mean(coords[:, 2])]) # Only merge site properties in both slabs site_properties = {} @@ -2766,9 +2765,7 @@ def label_termination(slab: Structure) -> str: for idx, cluster in enumerate(clusters): clustered_sites[cluster].append(slab[idx]) - plane_heights = { - np.average(np.mod([s.frac_coords[2] for s in sites], 1)): c for c, sites in clustered_sites.items() - } + plane_heights = {np.mean(np.mod([s.frac_coords[2] for s in sites], 1)): c for c, sites in clustered_sites.items()} top_plane_cluster = max(plane_heights.items(), key=lambda x: x[0])[1] top_plane_sites = clustered_sites[top_plane_cluster] top_plane = Structure.from_sites(top_plane_sites) @@ -2806,8 +2803,6 @@ def count_layers(struct: Structure, el=None) -> int: for idx, cluster in enumerate(clusters): clustered_sites[cluster].append(struct[idx]) - plane_heights = { - np.average(np.mod([s.frac_coords[2] for s in sites], 1)): c for c, sites in clustered_sites.items() - } + plane_heights = {np.mean(np.mod([s.frac_coords[2] for s in sites], 1)): c for c, sites in clustered_sites.items()} return len(plane_heights) diff --git a/pymatgen/core/ion.py b/pymatgen/core/ion.py index 4d4c7151c06..017b1963877 100644 --- a/pymatgen/core/ion.py +++ b/pymatgen/core/ion.py @@ -79,7 +79,7 @@ def from_formula(cls, formula: str) -> Self: @property def formula(self) -> str: """Returns a formula string with appended charge. The - charge is written with the sign preceding the magnitude, e.g., + charge is written with the sign preceding the magnitude, e.g. 'Ca1 +2'. Uncharged species have "(aq)" appended, e.g. "O2 (aq)". """ formula = super().formula @@ -182,7 +182,7 @@ def get_reduced_formula_and_factor(self, iupac_ordering: bool = False, hydrates: @property def reduced_formula(self) -> str: """Returns a reduced formula string with appended charge. The - charge is placed in brackets with the sign preceding the magnitude, e.g., + charge is placed in brackets with the sign preceding the magnitude, e.g. 'Ca[+2]'. Uncharged species have "(aq)" appended, e.g. "O2(aq)". """ formula, factor = self.get_reduced_formula_and_factor() @@ -228,7 +228,7 @@ def from_dict(cls, dct: dict) -> Self: def to_reduced_dict(self) -> dict: """ Returns: - dict with element symbol and reduced amount e.g., + dict with element symbol and reduced amount e.g. {"Fe": 2.0, "O":3.0}. """ dct = self.composition.to_reduced_dict @@ -249,7 +249,7 @@ def oxi_state_guesses( # type: ignore """Check if the composition is charge-balanced and returns back all charge-balanced oxidation state combinations. Composition must have integer values. Note that more num_atoms in the composition gives - more degrees of freedom. e.g., if possible oxidation states of + more degrees of freedom. e.g. if possible oxidation states of element X are [2,4] and Y are [-3], then XY is not charge balanced but X2Y2 is. Results are returned from most to least probable based on ICSD statistics. Use max_sites to improve performance if needed. diff --git a/pymatgen/core/lattice.py b/pymatgen/core/lattice.py index 5daf2d96ae6..4d8487bacba 100644 --- a/pymatgen/core/lattice.py +++ b/pymatgen/core/lattice.py @@ -1,4 +1,6 @@ -"""Defines the classes relating to 3D lattices.""" +"""This module defines the Lattice class, the fundamental class for representing +periodic crystals. It is essentially a matrix with some extra methods and attributes. +""" from __future__ import annotations @@ -53,7 +55,7 @@ def __init__(self, matrix: ArrayLike, pbc: PbcLike = (True, True, True)) -> None iii) [1, 0, 0 , 0, 1, 0, 0, 0, 1] iv) (1, 0, 0, 0, 1, 0, 0, 0, 1) Each row should correspond to a lattice vector. - E.g., [[10, 0, 0], [20, 10, 0], [0, 0, 30]] specifies a lattice + e.g. [[10, 0, 0], [20, 10, 0], [0, 0, 30]] specifies a lattice with lattice vectors [10, 0, 0], [20, 10, 0] and [0, 0, 30]. pbc: a tuple defining the periodic boundary conditions along the three axis of the lattice. @@ -107,7 +109,7 @@ def __format__(self, fmt_spec: str = "") -> str: """Support format printing. Supported fmt_spec (str) are: - 1. "l" for a list format that can be easily copied and pasted, e.g., + 1. "l" for a list format that can be easily copied and pasted, e.g. ".3fl" prints something like "[[10.000, 0.000, 0.000], [0.000, 10.000, 0.000], [0.000, 0.000, 10.000]]" 2. "p" for lattice parameters ".1fp" prints something like @@ -1504,7 +1506,7 @@ def get_all_distances( different functionality from pbc_diff. Args: - frac_coords1: First set of fractional coordinates. e.g., [0.5, 0.6, + frac_coords1: First set of fractional coordinates. e.g. [0.5, 0.6, 0.7] or [[1.1, 1.2, 4.3], [0.5, 0.6, 0.7]]. It can be a single coord or any array of coords. frac_coords2: Second set of fractional coordinates. @@ -1556,7 +1558,7 @@ def get_distance_and_image( frac_coords1 (3x1 array): Reference frac_coords to get distance from. frac_coords2 (3x1 array): frac_coords to get distance from. jimage (3x1 array): Specific periodic image in terms of - lattice translations, e.g., [1,0,0] implies to take periodic + lattice translations, e.g. [1,0,0] implies to take periodic image that is one a-lattice vector away. If jimage is None, the image that is nearest to the site is found. diff --git a/pymatgen/core/periodic_table.py b/pymatgen/core/periodic_table.py index c41a5565bc9..29f7154c40a 100644 --- a/pymatgen/core/periodic_table.py +++ b/pymatgen/core/periodic_table.py @@ -51,12 +51,12 @@ def __init__(self, symbol: SpeciesLike) -> None: represented by a None unless otherwise stated. Args: - symbol (str): Element symbol, e.g., "H", "Fe" + symbol (str): Element symbol, e.g. "H", "Fe" Attributes: Z (int): Atomic number. symbol (str): Element symbol. - long_name (str): Long name for element. E.g., "Hydrogen". + long_name (str): Long name for element. e.g. "Hydrogen". A (int) : Atomic mass number (number of protons plus neutrons). atomic_radius_calculated (float): Calculated atomic radius for the element. This is the empirical value. Data is obtained from http://wikipedia.org/wiki/Atomic_radii_of_the_elements_(data_page). @@ -73,9 +73,9 @@ def __init__(self, symbol: SpeciesLike) -> None: refractive_index (float): Refractive index. poissons_ratio (float): Poisson's ratio. molar_volume (float): Molar volume. - electronic_structure (str): Electronic structure. E.g., The electronic structure for Fe is represented + electronic_structure (str): Electronic structure. e.g. The electronic structure for Fe is represented as [Ar].3d6.4s2. - atomic_orbitals (dict): Atomic Orbitals. Energy of the atomic orbitals as a dict. E.g., The orbitals + atomic_orbitals (dict): Atomic Orbitals. Energy of the atomic orbitals as a dict. e.g. The orbitals energies in Hartree are represented as {'1s': -1.0, '2s': -0.1}. Data is obtained from https://www.nist.gov/pml/data/atomic-reference-data-electronic-structure-calculations. The LDA values for neutral atoms are used. @@ -290,7 +290,7 @@ def electron_affinity(self) -> float: @property def electronic_structure(self) -> str: """Electronic structure as string, with only valence electrons. - E.g., The electronic structure for Fe is represented as '[Ar].3d6.4s2'. + e.g. The electronic structure for Fe is represented as '[Ar].3d6.4s2'. """ return re.sub("", "", self._data["Electronic structure"]) @@ -378,7 +378,7 @@ def icsd_oxidation_states(self) -> tuple[int, ...]: @property def full_electronic_structure(self) -> list[tuple[int, str, int]]: """Full electronic structure as tuple. - E.g., The electronic structure for Fe is represented as: + e.g. The electronic structure for Fe is represented as: [(1, "s", 2), (2, "s", 2), (2, "p", 6), (3, "s", 2), (3, "p", 6), (3, "d", 6), (4, "s", 2)]. """ @@ -969,7 +969,7 @@ def __init__( self._spin = spin def __getattr__(self, attr: str) -> Any: - """Allows Specie to inherit properties of underlying element.""" + """Allow Specie to inherit properties of underlying element.""" return getattr(self._el, attr) def __getstate__(self) -> dict: @@ -1057,7 +1057,7 @@ def from_str(cls, species_string: str) -> Self: Args: species_string (str): A typical string representation of a - species, e.g., "Mn2+", "Fe3+", "O2-". + species, e.g. "Mn2+", "Fe3+", "O2-". Returns: A Species object. @@ -1289,7 +1289,7 @@ def __init__( rules are applied to the choice of the symbol. The dummy symbol cannot have any part of first two letters that will constitute an Element symbol. Otherwise, a composition may - be parsed wrongly. E.g., "X" is fine, but "Vac" is not + be parsed wrongly. e.g. "X" is fine, but "Vac" is not because Vac contains V, a valid Element. oxidation_state (float): Oxidation state for dummy specie. Defaults to 0. deprecated and retained purely for backward compatibility. @@ -1373,7 +1373,7 @@ def from_str(cls, species_string: str) -> Self: Args: species_string (str): A string representation of a dummy - species, e.g., "X2+", "X3+". + species, e.g. "X2+", "X3+". Returns: A DummySpecies object. diff --git a/pymatgen/core/sites.py b/pymatgen/core/sites.py index 7c84cd115de..41427a2e2bc 100644 --- a/pymatgen/core/sites.py +++ b/pymatgen/core/sites.py @@ -46,8 +46,8 @@ def __init__( i. A Composition-type object (preferred) ii. An element / species specified either as a string symbols, e.g. "Li", "Fe2+", "P" or atomic numbers, - e.g., 3, 56, or actual Element or Species objects. - iii.Dict of elements/species and occupancies, e.g., + e.g. 3, 56, or actual Element or Species objects. + iii.Dict of elements/species and occupancies, e.g. {"Fe" : 0.5, "Mn":0.5}. This allows the setup of disordered structures. coords: Cartesian coordinates of site. @@ -82,7 +82,7 @@ def __getattr__(self, attr): @property def species(self) -> Composition: - """The species on the site as a composition, e.g., Fe0.5Mn0.5.""" + """The species on the site as a composition, e.g. Fe0.5Mn0.5.""" return self._species @species.setter @@ -303,8 +303,8 @@ def __init__( i. A Composition-type object (preferred) ii. An element / species specified either as a string symbols, e.g. "Li", "Fe2+", "P" or atomic numbers, - e.g., 3, 56, or actual Element or Species objects. - iii.Dict of elements/species and occupancies, e.g., + e.g. 3, 56, or actual Element or Species objects. + iii.Dict of elements/species and occupancies, e.g. {"Fe" : 0.5, "Mn":0.5}. This allows the setup of disordered structures. coords: Coordinates of site, fractional coordinates @@ -500,7 +500,7 @@ def distance_and_image_from_frac_coords( Args: fcoords (3x1 array): fractional coordinates to get distance from. jimage (3x1 array): Specific periodic image in terms of - lattice translations, e.g., [1,0,0] implies to take periodic + lattice translations, e.g. [1,0,0] implies to take periodic image that is one a-lattice vector away. If jimage is None, the image that is nearest to the site is found. @@ -521,7 +521,7 @@ def distance_and_image(self, other: PeriodicSite, jimage: ArrayLike | None = Non Args: other (PeriodicSite): Other site to get distance from. jimage (3x1 array): Specific periodic image in terms of lattice - translations, e.g., [1,0,0] implies to take periodic image + translations, e.g. [1,0,0] implies to take periodic image that is one a-lattice vector away. If jimage is None, the image that is nearest to the site is found. @@ -537,7 +537,7 @@ def distance(self, other: PeriodicSite, jimage: ArrayLike | None = None): Args: other (PeriodicSite): Other site to get distance from. jimage (3x1 array): Specific periodic image in terms of lattice - translations, e.g., [1,0,0] implies to take periodic image + translations, e.g. [1,0,0] implies to take periodic image that is one a-lattice vector away. If jimage is None, the image that is nearest to the site is found. diff --git a/pymatgen/core/spectrum.py b/pymatgen/core/spectrum.py index 7e819edc397..7b28553caeb 100644 --- a/pymatgen/core/spectrum.py +++ b/pymatgen/core/spectrum.py @@ -19,7 +19,6 @@ def lorentzian(x, x_0: float = 0, sigma: float = 1.0): """ - Args: x: x values x_0: Center @@ -53,7 +52,7 @@ def __init__(self, x: ArrayLike, y: ArrayLike, *args, **kwargs) -> None: y (ndarray): A ndarray of N x k values. The first dimension must be the same as that of x. Each of the k values are interpreted as separate. *args: All subclasses should provide args other than x and y - when calling super, e.g., super().__init__( + when calling super, e.g. super().__init__( x, y, arg1, arg2, kwarg1=val1, ..). This guarantees the +, -, *, etc. operators work properly. **kwargs: Same as that for *args. @@ -81,7 +80,7 @@ def normalize(self, mode: Literal["max", "sum"] = "max", value: float = 1.0) -> Args: mode ("max" | "sum"): Normalization mode. "max" sets the max y value to value, - e.g., in XRD patterns. "sum" sets the sum of y to a value, i.e., like a + e.g. in XRD patterns. "sum" sets the sum of y to a value, i.e., like a probability density. value (float): Value to normalize to. Defaults to 1. """ diff --git a/pymatgen/core/structure.py b/pymatgen/core/structure.py index b5a62e7c28f..ad783a9144c 100644 --- a/pymatgen/core/structure.py +++ b/pymatgen/core/structure.py @@ -70,7 +70,7 @@ class Neighbor(Site): (site, nn_distance, index). - In future, usage should be to call attributes, e.g., Neighbor.index, Neighbor.distance, etc. + In future, usage should be to call attributes, e.g. Neighbor.index, Neighbor.distance, etc. """ def __init__( @@ -130,7 +130,7 @@ class PeriodicNeighbor(PeriodicSite): (site, distance, index, image). - In future, usage should be to call attributes, e.g., PeriodicNeighbor.index, + In future, usage should be to call attributes, e.g. PeriodicNeighbor.index, PeriodicNeighbor.distance, etc. """ @@ -560,7 +560,7 @@ def replace_species( Note that this clears the label of any affected site. Args: - species_mapping (dict): Species to swap. Species can be elements too. E.g., + species_mapping (dict): Species to swap. Species can be elements too. e.g. {Element("Li"): Element("Na")} performs a Li for Na substitution. The second species can be a sp_and_occu dict. For example, a site with 0.5 Si that is passed the mapping {Element('Si'): {Element('Ge'): 0.75, Element('C'): 0.25} } will have .375 Ge and .125 C. @@ -599,7 +599,7 @@ def add_oxidation_state_by_element(self, oxidation_states: dict[str, float]) -> Args: oxidation_states (dict): Dict of oxidation states. - E.g., {"Li":1, "Fe":2, "P":5, "O":-2} + e.g. {"Li":1, "Fe":2, "P":5, "O":-2} Raises: ValueError if oxidation states are not specified for all elements. @@ -969,16 +969,16 @@ def __init__( lattice (Lattice/3x3 array): The lattice, either as a pymatgen.core.Lattice or simply as any 2D array. Each row should correspond to a lattice - vector. E.g., [[10,0,0], [20,10,0], [0,0,30]] specifies a + vector. e.g. [[10,0,0], [20,10,0], [0,0,30]] specifies a lattice with lattice vectors [10,0,0], [20,10,0] and [0,0,30]. species ([Species]): Sequence of species on each site. Can take in flexible input, including: i. A sequence of element / species specified either as string symbols, e.g. ["Li", "Fe2+", "P", ...] or atomic numbers, - e.g., (3, 56, ...) or actual Element or Species objects. + e.g. (3, 56, ...) or actual Element or Species objects. - ii. List of dict of elements/species and occupancies, e.g., + ii. List of dict of elements/species and occupancies, e.g. [{"Fe" : 0.5, "Mn":0.5}, ...]. This allows the setup of disordered structures. coords (Nx3 array): list of fractional/Cartesian coordinates of @@ -1110,12 +1110,12 @@ def from_spacegroup( Args: sg (str/int): The spacegroup. If a string, it will be interpreted as one of the notations supported by - pymatgen.symmetry.groups.Spacegroup. E.g., "R-3c" or "Fm-3m". + pymatgen.symmetry.groups.Spacegroup. e.g. "R-3c" or "Fm-3m". If an int, it will be interpreted as an international number. lattice (Lattice/3x3 array): The lattice, either as a pymatgen.core.Lattice or simply as any 2D array. Each row should correspond to a lattice - vector. E.g., [[10,0,0], [20,10,0], [0,0,30]] specifies a + vector. e.g. [[10,0,0], [20,10,0], [0,0,30]] specifies a lattice with lattice vectors [10,0,0], [20,10,0] and [0,0,30]. Note that no attempt is made to check that the lattice is compatible with the spacegroup specified. This may be @@ -1125,9 +1125,9 @@ def from_spacegroup( i. A sequence of element / species specified either as string symbols, e.g. ["Li", "Fe2+", "P", ...] or atomic numbers, - e.g., (3, 56, ...) or actual Element or Species objects. + e.g. (3, 56, ...) or actual Element or Species objects. - ii. List of dict of elements/species and occupancies, e.g., + ii. List of dict of elements/species and occupancies, e.g. [{"Fe" : 0.5, "Mn":0.5}, ...]. This allows the setup of disordered structures. coords (Nx3 array): list of fractional/cartesian coordinates of @@ -1135,7 +1135,7 @@ def from_spacegroup( coords_are_cartesian (bool): Set to True if you are providing coordinates in Cartesian coordinates. Defaults to False. site_properties (dict): Properties associated with the sites as a - dict of sequences, e.g., {"magmom":[5,5,5,5]}. The sequences + dict of sequences, e.g. {"magmom":[5,5,5,5]}. The sequences have to be the same length as the atomic species and fractional_coords. Defaults to None for no properties. tol (float): A fractional tolerance to deal with numerical @@ -1205,13 +1205,13 @@ def from_magnetic_spacegroup( msg (str/list/pymatgen.symmetry.maggroups.MagneticSpaceGroup): The magnetic spacegroup. If a string, it will be interpreted as one of the notations - supported by MagneticSymmetryGroup, e.g., "R-3'c" or "Fm'-3'm". + supported by MagneticSymmetryGroup, e.g. "R-3'c" or "Fm'-3'm". If a list of two ints, it will be interpreted as the number of the spacegroup in its Belov, Neronova and Smirnova (BNS) setting. lattice (Lattice/3x3 array): The lattice, either as a pymatgen.core.Lattice or simply as any 2D array. Each row should correspond to a lattice - vector. E.g., [[10,0,0], [20,10,0], [0,0,30]] specifies a + vector. e.g. [[10,0,0], [20,10,0], [0,0,30]] specifies a lattice with lattice vectors [10,0,0], [20,10,0] and [0,0,30]. Note that no attempt is made to check that the lattice is compatible with the spacegroup specified. This may be @@ -1220,15 +1220,15 @@ def from_magnetic_spacegroup( flexible input, including: i. A sequence of element / species specified either as string symbols, e.g. ["Li", "Fe2+", "P", ...] or atomic numbers, - e.g., (3, 56, ...) or actual Element or Species objects. + e.g. (3, 56, ...) or actual Element or Species objects. - ii. List of dict of elements/species and occupancies, e.g., + ii. List of dict of elements/species and occupancies, e.g. [{"Fe" : 0.5, "Mn":0.5}, ...]. This allows the setup of disordered structures. coords (Nx3 array): list of fractional/cartesian coordinates of each species. site_properties (dict): Properties associated with the sites as a - dict of sequences, e.g., {"magmom":[5,5,5,5]}. The sequences + dict of sequences, e.g. {"magmom":[5,5,5,5]}. The sequences have to be the same length as the atomic species and fractional_coords. Unlike Structure.from_spacegroup(), this argument is mandatory, since magnetic moment information @@ -1424,11 +1424,11 @@ def __mul__(self, scaling_matrix: int | Sequence[int] | Sequence[Sequence[int]]) vectors. Has to be all integers. Several options are possible: a. A full 3x3 scaling matrix defining the linear combination - of the old lattice vectors. E.g., [[2,1,0],[0,3,0],[0,0, + of the old lattice vectors. e.g. [[2,1,0],[0,3,0],[0,0, 1]] generates a new structure with lattice vectors a' = 2a + b, b' = 3b, c' = c where a, b, and c are the lattice vectors of the original structure. - b. A sequence of three scaling factors. E.g., [2, 1, 1] + b. A sequence of three scaling factors. e.g. [2, 1, 1] specifies that the supercell should have dimensions 2a x b x c. c. A number, which simply scales all lattice vectors by the @@ -1724,7 +1724,7 @@ def get_symmetric_neighbor_list( sg (str/int): The spacegroup the symmetry operations of which will be used to classify the neighbors. If a string, it will be interpreted as one of the notations supported by - pymatgen.symmetry.groups.Spacegroup. E.g., "R-3c" or "Fm-3m". + pymatgen.symmetry.groups.Spacegroup. e.g. "R-3c" or "Fm-3m". If an int, it will be interpreted as an international number. If None, 'get_space_group_info' will be used to determine the space group, default to None. @@ -2672,7 +2672,7 @@ def as_dict(self, verbosity=1, fmt=None, **kwargs) -> dict[str, Any]: which is the default format used in pymatgen. Other options include "abivars". **kwargs: Allow passing of other kwargs needed for certain - formats, e.g., "abivars". + formats, e.g. "abivars". Returns: JSON-serializable dict representation. @@ -2762,7 +2762,7 @@ def to(self, filename: str | Path = "", fmt: FileFormats = "", **kwargs) -> str: filename is. Options include "cif", "poscar", "cssr", "json", "xsf", "mcsqs", "prismatic", "yaml", "yml", "fleur-inpgen", "pwmat". Non-case sensitive. - **kwargs: Kwargs passthru to relevant methods. E.g., This allows + **kwargs: Kwargs passthru to relevant methods. e.g. This allows the passing of parameters like symprec to the CifWriter.__init__ method for generation of symmetric CIFs. @@ -3109,7 +3109,7 @@ def __init__( validate_proximity (bool): Whether to check if there are sites that are less than 1 Ang apart. Defaults to False. site_properties (dict): Properties associated with the sites as - a dict of sequences, e.g., {"magmom":[5,5,5,5]}. The + a dict of sequences, e.g. {"magmom":[5,5,5,5]}. The sequences have to be the same length as the atomic species and fractional_coords. Defaults to None for no properties. labels (list[str]): Labels associated with the sites as a @@ -3755,16 +3755,16 @@ def __init__( Args: lattice: The lattice, either as a pymatgen.core.Lattice or simply as any 2D array. Each row should correspond to a lattice - vector. E.g., [[10,0,0], [20,10,0], [0,0,30]] specifies a + vector. e.g. [[10,0,0], [20,10,0], [0,0,30]] specifies a lattice with lattice vectors [10,0,0], [20,10,0] and [0,0,30]. species: List of species on each site. Can take in flexible input, including: i. A sequence of element / species specified either as string symbols, e.g. ["Li", "Fe2+", "P", ...] or atomic numbers, - e.g., (3, 56, ...) or actual Element or Species objects. + e.g. (3, 56, ...) or actual Element or Species objects. - ii. List of dict of elements/species and occupancies, e.g., + ii. List of dict of elements/species and occupancies, e.g. [{"Fe" : 0.5, "Mn":0.5}, ...]. This allows the setup of disordered structures. coords (Nx3 array): list of fractional/cartesian coordinates of @@ -3779,7 +3779,7 @@ def __init__( coords_are_cartesian (bool): Set to True if you are providing coordinates in Cartesian coordinates. Defaults to False. site_properties (dict): Properties associated with the sites as a - dict of sequences, e.g., {"magmom":[5,5,5,5]}. The sequences + dict of sequences, e.g. {"magmom":[5,5,5,5]}. The sequences have to be the same length as the atomic species and fractional_coords. Defaults to None for no properties. labels (list[str]): Labels associated with the sites as a @@ -4101,7 +4101,7 @@ def remove_species(self, species: Sequence[SpeciesLike]) -> Self: """Remove all occurrences of several species from a structure. Args: - species: Sequence of species to remove, e.g., ["Li", "Na"]. + species: Sequence of species to remove, e.g. ["Li", "Na"]. Returns: Structure: self with species removed. @@ -4190,7 +4190,7 @@ def apply_strain(self, strain: ArrayLike, inplace: bool = True) -> Structure: Args: strain (float or list): Amount of strain to apply. Can be a float, - or a sequence of 3 numbers. E.g., 0.01 means all lattice + or a sequence of 3 numbers. e.g. 0.01 means all lattice vectors are increased by 1%. This is equivalent to calling modify_lattice with a lattice with lattice parameters that are 1% larger. @@ -4350,11 +4350,11 @@ def make_supercell(self, scaling_matrix: ArrayLike, to_unit_cell: bool = True, i vectors. Has to be all integers. Several options are possible: a. A full 3x3 scaling matrix defining the linear combination - the old lattice vectors. E.g., [[2,1,0],[0,3,0],[0,0, + the old lattice vectors. e.g. [[2,1,0],[0,3,0],[0,0, 1]] generates a new structure with lattice vectors a' = 2a + b, b' = 3b, c' = c where a, b, and c are the lattice vectors of the original structure. - b. An sequence of three scaling factors. E.g., [2, 1, 1] + b. An sequence of three scaling factors. e.g. [2, 1, 1] specifies that the supercell should have dimensions 2a x b x c. c. A number, which simply scales all lattice vectors by the @@ -4511,9 +4511,9 @@ def from_prototype(cls, prototype: str, species: Sequence, **kwargs) -> Self: """Method to rapidly construct common prototype structures. Args: - prototype: Name of prototype. E.g., cubic, rocksalt, perovksite etc. + prototype: Name of prototype. e.g. cubic, rocksalt, perovksite etc. species: List of species corresponding to symmetrically distinct sites. - **kwargs: Lattice parameters, e.g., a = 3.0, b = 4, c = 5. Only the required lattice parameters need to be + **kwargs: Lattice parameters, e.g. a = 3.0, b = 4, c = 5. Only the required lattice parameters need to be specified. For example, if it is a cubic prototype, only a needs to be specified. Returns: @@ -4596,7 +4596,7 @@ def __init__( validate_proximity (bool): Whether to check if there are sites that are less than 1 Ang apart. Defaults to False. site_properties (dict): Properties associated with the sites as - a dict of sequences, e.g., {"magmom":[5,5,5,5]}. The + a dict of sequences, e.g. {"magmom":[5,5,5,5]}. The sequences have to be the same length as the atomic species and fractional_coords. Defaults to None for no properties. labels (list[str]): Labels associated with the sites as a @@ -4634,7 +4634,7 @@ def __setitem__( # type: ignore site (PeriodicSite/Species/Sequence): Three options exist. You can provide a Site directly, or for convenience, you can provide simply a Species-like string/object, or finally a (Species, - coords) sequence, e.g., ("Fe", [0.5, 0.5, 0.5]). + coords) sequence, e.g. ("Fe", [0.5, 0.5, 0.5]). """ if isinstance(idx, int): indices = [idx] @@ -5036,7 +5036,7 @@ def calculate(self, calculator: str | Calculator = "gfn2-xtb", verbose: bool = F class StructureError(Exception): """Exception class for Structure. - Raised when the structure has problems, e.g., atoms that are too close. + Raised when the structure has problems, e.g. atoms that are too close. """ diff --git a/pymatgen/core/surface.py b/pymatgen/core/surface.py index d65a266bf48..831b809f5ea 100644 --- a/pymatgen/core/surface.py +++ b/pymatgen/core/surface.py @@ -96,15 +96,15 @@ def __init__( lattice (Lattice/3x3 array): The lattice, either as a pymatgen.core.Lattice or simply as any 2D array. Each row should correspond to a lattice - vector. E.g., [[10,0,0], [20,10,0], [0,0,30]]. + vector. e.g. [[10,0,0], [20,10,0], [0,0,30]]. species ([Species]): Sequence of species on each site. Can take in flexible input, including: i. A sequence of element / species specified either as string symbols, e.g. ["Li", "Fe2+", "P", ...] or atomic numbers, - e.g., (3, 56, ...) or actual Element or Species objects. + e.g. (3, 56, ...) or actual Element or Species objects. - ii. List of dict of elements/species and occupancies, e.g., + ii. List of dict of elements/species and occupancies, e.g. [{"Fe": 0.5, "Mn": 0.5}, ...]. This allows the setup of disordered structures. coords (Nx3 array): list of fractional/cartesian coordinates of each species. @@ -128,7 +128,7 @@ def __init__( coords_are_cartesian (bool): Set to True if you are providing coordinates in Cartesian coordinates. Defaults to False. site_properties (dict): Properties associated with the sites as a - dict of sequences, e.g., {"magmom":[5,5,5,5]}. The sequences + dict of sequences, e.g. {"magmom":[5,5,5,5]}. The sequences have to be the same length as the atomic species and fractional_coords. Defaults to None for no properties. energy (float): A value for the energy. @@ -1150,7 +1150,7 @@ def get_slab(self, shift: float = 0, tol: float = 0.1, energy: float | None = No # Center the slab layer around the vacuum if self.center_slab: - c_center = np.average([coord[2] for coord in slab.frac_coords]) + c_center = np.mean([coord[2] for coord in slab.frac_coords]) slab.translate_sites(list(range(len(slab))), [0, 0, 0.5 - c_center]) # Reduce to primitive cell diff --git a/pymatgen/core/tensors.py b/pymatgen/core/tensors.py index 09509a87c86..5cd75667ca2 100644 --- a/pymatgen/core/tensors.py +++ b/pymatgen/core/tensors.py @@ -185,7 +185,7 @@ def get_grouped_indices(self, voigt=False, **kwargs): of voigt or full notation tensor, defaults to false **kwargs: keyword args for np.isclose. Can take atol - and rtol for absolute and relative tolerance, e. g. + and rtol for absolute and relative tolerance, e.g. >>> tensor.group_array_indices(atol=1e-8) @@ -223,7 +223,7 @@ def get_symbol_dict(self, voigt=True, zero_index=False, **kwargs): defaults to false, since tensor notations tend to use one-indexing, rather than zero indexing like python **kwargs: keyword args for np.isclose. Can take atol - and rtol for absolute and relative tolerance, e. g. + and rtol for absolute and relative tolerance, e.g. >>> tensor.get_symbol_dict(atol=1e-8) @@ -284,7 +284,7 @@ def voigt_symmetrized(self): return type(self).from_voigt(new_v) def is_symmetric(self, tol: float = 1e-5): - """Tests whether a tensor is symmetric or not based on the residual + """Test whether a tensor is symmetric or not based on the residual with its symmetric part, from self.symmetrized. Args: @@ -307,7 +307,7 @@ def fit_to_structure(self, structure: Structure, symprec: float = 0.1): return sum(self.transform(symm_op) for symm_op in symm_ops) / len(symm_ops) def is_fit_to_structure(self, structure: Structure, tol: float = 1e-2): - """Tests whether a tensor is invariant with respect to the + """Test whether a tensor is invariant with respect to the symmetry operations of a particular structure by testing whether the residual of the symmetric portion is below a tolerance. @@ -330,7 +330,7 @@ def voigt(self): return v_matrix * self._vscale def is_voigt_symmetric(self, tol: float = 1e-6) -> bool: - """Tests symmetry of tensor to that necessary for voigt-conversion + """Test symmetry of tensor to that necessary for voigt-conversion by grouping indices into pairs and constructing a sequence of possible permutations to be used in a tensor transpose. """ diff --git a/pymatgen/core/trajectory.py b/pymatgen/core/trajectory.py index 4b39f347980..925020f4297 100644 --- a/pymatgen/core/trajectory.py +++ b/pymatgen/core/trajectory.py @@ -61,8 +61,8 @@ def __init__( input, including: i. A sequence of element / species specified either as string symbols, e.g. ["Li", "Fe2+", "P", ...] or atomic numbers, - e.g., (3, 56, ...) or actual Element or Species objects. - ii. List of dict of elements/species and occupancies, e.g., + e.g. (3, 56, ...) or actual Element or Species objects. + ii. List of dict of elements/species and occupancies, e.g. [{"Fe" : 0.5, "Mn":0.5}, ...]. This allows the setup of disordered structures. coords: shape (M, N, 3). fractional coordinates of the sites. diff --git a/pymatgen/core/units.py b/pymatgen/core/units.py index 5f0e4044b7f..0b5958b011b 100644 --- a/pymatgen/core/units.py +++ b/pymatgen/core/units.py @@ -161,7 +161,7 @@ def _check_mappings(u): class Unit(collections.abc.Mapping): - """Represents a unit, e.g., "m" for meters, etc. Supports compound units. + """Represents a unit, e.g. "m" for meters, etc. Supports compound units. Only integer powers are supported for units. """ @@ -169,7 +169,7 @@ def __init__(self, unit_def) -> None: """ Args: unit_def: A definition for the unit. Either a mapping of unit to - powers, e.g., {"m": 2, "s": -1} represents "m^2 s^-1", + powers, e.g. {"m": 2, "s": -1} represents "m^2 s^-1", or simply as a string "kg m^2 s^-1". Note that the supported format uses "^" as the power operator and all units must be space-separated. @@ -273,7 +273,7 @@ class FloatWithUnit(float): pre-defined unit type subclasses such as Energy, Length, etc. instead of using FloatWithUnit directly. - Supports conversion, addition and subtraction of the same unit type. E.g., + Supports conversion, addition and subtraction of the same unit type. e.g. 1 m + 20 cm will be automatically converted to 1.2 m (units follow the leftmost quantity). Note that FloatWithUnit does not override the eq method for float, i.e., units are not checked when testing for equality. @@ -295,8 +295,8 @@ def __init__(self, val: float | Number, unit: str, unit_type: str | None = None) Args: val (float): Value - unit (Unit): A unit. E.g., "C". - unit_type (str): A type of unit. E.g., "charge" + unit (Unit): A unit. e.g. "C". + unit_type (str): A type of unit. e.g. "charge" """ if unit_type is not None and str(unit) not in ALL_UNITS[unit_type]: raise UnitError(f"{unit} is not a supported unit for {unit_type}") @@ -383,7 +383,7 @@ def unit_type(self) -> str | None: @property def unit(self) -> Unit: - """The unit, e.g., "eV".""" + """The unit, e.g. "eV".""" return self._unit @classmethod @@ -448,7 +448,7 @@ class ArrayWithUnit(np.ndarray): use the pre-defined unit type subclasses such as EnergyArray, LengthArray, etc. instead of using ArrayWithFloatWithUnit directly. - Supports conversion, addition and subtraction of the same unit type. E.g., + Supports conversion, addition and subtraction of the same unit type. e.g. 1 m + 20 cm will be automatically converted to 1.2 m (units follow the leftmost quantity). @@ -487,7 +487,7 @@ def unit_type(self) -> str: @property def unit(self) -> str: - """The unit, e.g., "eV".""" + """The unit, e.g. "eV".""" return self._unit def __reduce__(self): @@ -624,7 +624,7 @@ def _my_partial(func, *args, **kwargs): Args: val (float): Value - unit (Unit): E.g., eV, kJ, etc. Must be valid unit or UnitError is raised. + unit (Unit): e.g. eV, kJ, etc. Must be valid unit or UnitError is raised. """ EnergyArray = partial(ArrayWithUnit, unit_type="energy") @@ -634,7 +634,7 @@ def _my_partial(func, *args, **kwargs): Args: val (float): Value - unit (Unit): E.g., m, ang, bohr, etc. Must be valid unit or UnitError is + unit (Unit): e.g. m, ang, bohr, etc. Must be valid unit or UnitError is raised. """ LengthArray = partial(ArrayWithUnit, unit_type="length") @@ -645,7 +645,7 @@ def _my_partial(func, *args, **kwargs): Args: val (float): Value - unit (Unit): E.g., amu, kg, etc. Must be valid unit or UnitError is + unit (Unit): e.g. amu, kg, etc. Must be valid unit or UnitError is raised. """ MassArray = partial(ArrayWithUnit, unit_type="mass") @@ -656,7 +656,7 @@ def _my_partial(func, *args, **kwargs): Args: val (float): Value - unit (Unit): E.g., K. Only K (kelvin) is supported. + unit (Unit): e.g. K. Only K (kelvin) is supported. """ TempArray = partial(ArrayWithUnit, unit_type="temperature") @@ -666,7 +666,7 @@ def _my_partial(func, *args, **kwargs): Args: val (float): Value - unit (Unit): E.g., s, min, h. Must be valid unit or UnitError is + unit (Unit): e.g. s, min, h. Must be valid unit or UnitError is raised. """ TimeArray = partial(ArrayWithUnit, unit_type="time") @@ -677,7 +677,7 @@ def _my_partial(func, *args, **kwargs): Args: val (float): Value - unit (Unit): E.g., C, e (electron charge). Must be valid unit or UnitError + unit (Unit): e.g. C, e (electron charge). Must be valid unit or UnitError is raised. """ ChargeArray = partial(ArrayWithUnit, unit_type="charge") @@ -688,7 +688,7 @@ def _my_partial(func, *args, **kwargs): Args: val (float): Value - unit (Unit): E.g., Kb, Mb, Gb, Tb. Must be valid unit or UnitError + unit (Unit): e.g. Kb, Mb, Gb, Tb. Must be valid unit or UnitError is raised. """ diff --git a/pymatgen/electronic_structure/bandstructure.py b/pymatgen/electronic_structure/bandstructure.py index 49c822ac9f9..4479c4cbd82 100644 --- a/pymatgen/electronic_structure/bandstructure.py +++ b/pymatgen/electronic_structure/bandstructure.py @@ -261,7 +261,7 @@ def get_projections_on_elements_and_orbitals(self, el_orb_spec): Args: el_orb_spec: A dictionary of Elements and Orbitals for which we want to have projections on. It is given as: {Element:[orbitals]}, - e.g., {'Cu':['d','s']} + e.g. {'Cu':['d','s']} Returns: A dictionary of projections on elements in the @@ -1033,7 +1033,7 @@ def get_projections_on_elements_and_orbitals(self, el_orb_spec): Args: el_orb_spec: A dictionary of Elements and Orbitals for which we want to have projections on. It is given as: {Element:[orbitals]}, - e.g., {'Si':['3s','3p']} or {'Si':['3s','3p_x', '3p_y', '3p_z']} depending on input files + e.g. {'Si':['3s','3p']} or {'Si':['3s','3p_x', '3p_y', '3p_z']} depending on input files Returns: A dictionary of projections on elements in the diff --git a/pymatgen/electronic_structure/boltztrap.py b/pymatgen/electronic_structure/boltztrap.py index ebb8425720c..cdf9700b183 100644 --- a/pymatgen/electronic_structure/boltztrap.py +++ b/pymatgen/electronic_structure/boltztrap.py @@ -450,7 +450,7 @@ def write_intrans(self, output_file) -> None: fout.write(".15 # (efcut) energy range of chemical potential\n") fout.write(f"{self.tmax} {self.tgrid} # Tmax, temperature grid\n") fout.write("-1. # energyrange of bands given DOS output sig_xxx and dos_xxx (xxx is band number)\n") - fout.write(self.dos_type + "\n") # e.g., HISTO or TETRA + fout.write(self.dos_type + "\n") # e.g. HISTO or TETRA fout.write(f"{self.tauref} {self.tauexp} {self.tauen} 0 0 0\n") fout.write(f"{2 * len(self.doping)}\n") @@ -1668,7 +1668,7 @@ def get_hall_carrier_concentration(self): @staticmethod def parse_outputtrans(path_dir): - """Parses .outputtrans file. + """Parse .outputtrans file. Args: path_dir: dir containing boltztrap.outputtrans @@ -1696,7 +1696,7 @@ def parse_outputtrans(path_dir): @staticmethod def parse_transdos(path_dir, efermi, dos_spin=1, trim_dos=False): - """Parses .transdos (total DOS) and .transdos_x_y (partial DOS) files. + """Parse .transdos (total DOS) and .transdos_x_y (partial DOS) files. Args: path_dir: (str) dir containing DOS files @@ -1771,7 +1771,7 @@ def parse_transdos(path_dir, efermi, dos_spin=1, trim_dos=False): @staticmethod def parse_intrans(path_dir): - """Parses boltztrap.intrans mainly to extract the value of scissor applied + """Parse boltztrap.intrans mainly to extract the value of scissor applied to the bands or some other inputs. Args: @@ -1791,7 +1791,7 @@ def parse_intrans(path_dir): @staticmethod def parse_struct(path_dir): - """Parses boltztrap.struct file (only the volume). + """Parse boltztrap.struct file (only the volume). Args: path_dir: (str) dir containing the boltztrap.struct file @@ -1807,7 +1807,7 @@ def parse_struct(path_dir): @staticmethod def parse_cond_and_hall(path_dir, doping_levels=None): - """Parses the conductivity and Hall tensors. + """Parse the conductivity and Hall tensors. Args: path_dir: Path containing .condtens / .halltens files @@ -2151,7 +2151,6 @@ def _make_float_hall(a): def read_cube_file(filename): """ - Args: filename: Cube filename. diff --git a/pymatgen/electronic_structure/cohp.py b/pymatgen/electronic_structure/cohp.py index 88b629ed6d2..252ae4c24f0 100644 --- a/pymatgen/electronic_structure/cohp.py +++ b/pymatgen/electronic_structure/cohp.py @@ -770,7 +770,7 @@ def from_file( for i in avg_data: for spin in spins: rows = np.array([v[i][spin] for v in cohp_data.values()]) - avg = np.average(rows, axis=0) + avg = np.mean(rows, axis=0) # LMTO COHPs have 5 significant figures avg_data[i].update({spin: np.array([round_to_sigfigs(a, 5) for a in avg], dtype=float)}) avg_cohp = Cohp(efermi, energies, avg_data["COHP"], icohp=avg_data["ICOHP"]) diff --git a/pymatgen/electronic_structure/core.py b/pymatgen/electronic_structure/core.py index 27ca90801fb..784e34628a1 100644 --- a/pymatgen/electronic_structure/core.py +++ b/pymatgen/electronic_structure/core.py @@ -231,12 +231,8 @@ def get_moment(self, saxis=(0, 0, 1)): return moment @property - def global_moment(self): - """Get the magnetic moment defined in an arbitrary global reference frame. - - Returns: - np.ndarray of length 3 - """ + def global_moment(self) -> np.ndarray: + """The magnetic moment defined in an arbitrary global reference frame as an np.array of length 3.""" return self.get_moment() @property diff --git a/pymatgen/electronic_structure/dos.py b/pymatgen/electronic_structure/dos.py index 77cf25efa1a..8d7538cbac9 100644 --- a/pymatgen/electronic_structure/dos.py +++ b/pymatgen/electronic_structure/dos.py @@ -34,7 +34,7 @@ class DOS(Spectrum): Attributes: energies (Sequence[float]): The sequence of energies. - densities (dict[Spin, Sequence[float]]): A dict of spin densities, e.g., {Spin.up: [...], Spin.down: [...]}. + densities (dict[Spin, Sequence[float]]): A dict of spin densities, e.g. {Spin.up: [...], Spin.down: [...]}. efermi (float): Fermi level. """ @@ -168,7 +168,7 @@ class Dos(MSONable): Attributes: energies (Sequence[float]): The sequence of energies. - densities (dict[Spin, Sequence[float]]): A dict of spin densities, e.g., {Spin.up: [...], Spin.down: [...]}. + densities (dict[Spin, Sequence[float]]): A dict of spin densities, e.g. {Spin.up: [...], Spin.down: [...]}. efermi (float): Fermi level. """ diff --git a/pymatgen/entries/compatibility.py b/pymatgen/entries/compatibility.py index e92ee2ad6df..0bfac3bca84 100644 --- a/pymatgen/entries/compatibility.py +++ b/pymatgen/entries/compatibility.py @@ -296,7 +296,7 @@ def get_correction(self, entry) -> ufloat: else: warnings.warn( "No structure or oxide_type parameter present. Note that peroxide/superoxide corrections " - "are not as reliable and relies only on detection of special formulas, e.g., Li2O2." + "are not as reliable and relies only on detection of special formulas, e.g. Li2O2." ) rform = entry.reduced_formula if rform in UCorrection.common_peroxides: @@ -994,7 +994,7 @@ def get_adjustments(self, entry: AnyComputedEntry) -> list[EnergyAdjustment]: else: warnings.warn( "No structure or oxide_type parameter present. Note that peroxide/superoxide corrections " - "are not as reliable and relies only on detection of special formulas, e.g., Li2O2." + "are not as reliable and relies only on detection of special formulas, e.g. Li2O2." ) common_peroxides = "Li2O2 Na2O2 K2O2 Cs2O2 Rb2O2 BeO2 MgO2 CaO2 SrO2 BaO2".split() diff --git a/pymatgen/entries/computed_entries.py b/pymatgen/entries/computed_entries.py index 4afc15b5bf3..af279af77a8 100644 --- a/pymatgen/entries/computed_entries.py +++ b/pymatgen/entries/computed_entries.py @@ -776,7 +776,7 @@ def gf_sisso(self) -> float: Returns: float: the difference between formation enthalpy (T=0 K, Materials - Project) and the predicted Gibbs free energy of formation (eV) + Project) and the predicted Gibbs free energy of formation (eV) """ comp = self.composition diff --git a/pymatgen/entries/correction_calculator.py b/pymatgen/entries/correction_calculator.py index 5f707373041..070a5f0ef37 100644 --- a/pymatgen/entries/correction_calculator.py +++ b/pymatgen/entries/correction_calculator.py @@ -97,7 +97,7 @@ def compute_from_files(self, exp_gz: str, comp_gz: str): return self.compute_corrections(exp_entries, calc_entries) def compute_corrections(self, exp_entries: list, calc_entries: dict) -> dict: - """Computes the corrections and fills in correction, corrections_std_error, and corrections_dict. + """Compute the corrections and fills in correction, corrections_std_error, and corrections_dict. Args: exp_entries: list of dictionary objects with the following keys/values: diff --git a/pymatgen/entries/entry_tools.py b/pymatgen/entries/entry_tools.py index 7438303da01..1c4b30b025c 100644 --- a/pymatgen/entries/entry_tools.py +++ b/pymatgen/entries/entry_tools.py @@ -231,7 +231,7 @@ def discard(self, element): def chemsys(self) -> set: """ Returns: - set representing the chemical system, e.g., {"Li", "Fe", "P", "O"}. + set representing the chemical system, e.g. {"Li", "Fe", "P", "O"}. """ chemsys = set() for e in self.entries: @@ -267,7 +267,7 @@ def get_subset_in_chemsys(self, chemsys: list[str]): and Li-O entries are returned. Args: - chemsys: Chemical system specified as list of elements. E.g., + chemsys: Chemical system specified as list of elements. e.g. ["Li", "O"] Returns: @@ -296,7 +296,7 @@ def to_csv(self, filename: str, latexify_names: bool = False) -> None: filename: Filename to write to. entries: PDEntries to export. latexify_names: Format entry names to be LaTex compatible, - e.g., Li_{2}O + e.g. Li_{2}O """ els: set[Element] = set() for entry in self.entries: diff --git a/pymatgen/ext/cod.py b/pymatgen/ext/cod.py index 190b9940488..df3094af4e0 100644 --- a/pymatgen/ext/cod.py +++ b/pymatgen/ext/cod.py @@ -58,7 +58,7 @@ def query(self, sql: str) -> str: @requires(which("mysql"), "mysql must be installed to use this query.") def get_cod_ids(self, formula) -> list[int]: - """Queries the COD for all cod ids associated with a formula. Requires + """Query the COD for all cod ids associated with a formula. Requires mysql executable to be in the path. Args: @@ -81,7 +81,7 @@ def get_cod_ids(self, formula) -> list[int]: return cod_ids def get_structure_by_id(self, cod_id: int, timeout: int = 600, **kwargs) -> Structure: - """Queries the COD for a structure by id. + """Query the COD for a structure by id. Args: cod_id (int): COD id. @@ -96,7 +96,7 @@ def get_structure_by_id(self, cod_id: int, timeout: int = 600, **kwargs) -> Stru @requires(which("mysql"), "mysql must be installed to use this query.") def get_structure_by_formula(self, formula: str, **kwargs) -> list[dict[str, str | int | Structure]]: - """Queries the COD for structures by formula. Requires mysql executable to + """Query the COD for structures by formula. Requires mysql executable to be in the path. Args: diff --git a/pymatgen/ext/matproj.py b/pymatgen/ext/matproj.py index 3daf8194383..17b605db840 100644 --- a/pymatgen/ext/matproj.py +++ b/pymatgen/ext/matproj.py @@ -157,7 +157,7 @@ def get_summary(self, criteria: dict, fields: list | None = None) -> list[dict]: """Get a data corresponding to a criteria. Args: - criteria (dict): Materials Project ID (e.g. mp-1234), e.g., {"formula": "Fe2O3,FeO"} + criteria (dict): Materials Project ID (e.g. mp-1234), e.g. {"formula": "Fe2O3,FeO"} fields (list): Fields to query for. If None (the default), all fields are returned. Returns: @@ -315,7 +315,7 @@ def get_entry_by_material_id(self, material_id: str, *args, **kwargs) -> Compute Args: material_id (str): Materials Project material_id (a string, - e.g., mp-1234). + e.g. mp-1234). *args: Pass-through to get_entries. **kwargs: Pass-through to get_entries. @@ -332,8 +332,8 @@ def get_entries_in_chemsys(self, elements, *args, **kwargs): Args: elements (str or [str]): Chemical system string comprising element - symbols separated by dashes, e.g., "Li-Fe-O" or List of element - symbols, e.g., ["Li", "Fe", "O"]. + symbols separated by dashes, e.g. "Li-Fe-O" or List of element + symbols, e.g. ["Li", "Fe", "O"]. *args: Pass-through to get_entries. **kwargs: Pass-through to get_entries. diff --git a/pymatgen/ext/matproj_legacy.py b/pymatgen/ext/matproj_legacy.py index e2e2f4c0eb3..8df0ec2ca12 100644 --- a/pymatgen/ext/matproj_legacy.py +++ b/pymatgen/ext/matproj_legacy.py @@ -360,7 +360,7 @@ def get_doc(self, materials_id): REST Endpoint: https://materialsproject.org/materials//doc. Args: - materials_id (str): E.g., mp-1143 for Al2O3 + materials_id (str): e.g. mp-1143 for Al2O3 Returns: Dict of json document of all data that is displayed on a materials @@ -377,9 +377,9 @@ def get_xas_data(self, material_id, absorbing_element): https://materialsproject.org/materials//xas/. Args: - material_id (str): E.g., mp-1143 for Al2O3 + material_id (str): e.g. mp-1143 for Al2O3 absorbing_element (str): The absorbing element in the corresponding - structure. E.g., Al in Al2O3 + structure. e.g. Al in Al2O3 """ element_list = self.get_data(material_id, prop="elements")[0]["elements"] if absorbing_element not in element_list: @@ -575,8 +575,8 @@ def get_pourbaix_entries(self, chemsys, solid_compat="MaterialsProject2020Compat Args: chemsys (str or [str]): Chemical system string comprising element - symbols separated by dashes, e.g., "Li-Fe-O" or List of element - symbols, e.g., ["Li", "Fe", "O"]. + symbols separated by dashes, e.g. "Li-Fe-O" or List of element + symbols, e.g. ["Li", "Fe", "O"]. solid_compat: Compatibility scheme used to pre-process solid DFT energies prior to applying aqueous energy adjustments. May be passed as a class (e.g. MaterialsProject2020Compatibility) or an instance (e.g., MaterialsProject2020Compatibility()). If None, solid DFT energies are used as-is. @@ -718,7 +718,7 @@ def get_entry_by_material_id( Args: material_id (str): Materials Project material_id (a string, - e.g., mp-1234). + e.g. mp-1234). compatible_only (bool): Whether to return only "compatible" entries. Compatible entries are entries that have been processed using the MaterialsProject2020Compatibility class, @@ -760,7 +760,7 @@ def get_dos_by_material_id(self, material_id): Args: material_id (str): Materials Project material_id (a string, - e.g., mp-1234). + e.g. mp-1234). Returns: A Dos object. @@ -836,8 +836,8 @@ def get_entries_in_chemsys( Args: elements (str or [str]): Chemical system string comprising element - symbols separated by dashes, e.g., "Li-Fe-O" or List of element - symbols, e.g., ["Li", "Fe", "O"]. + symbols separated by dashes, e.g. "Li-Fe-O" or List of element + symbols, e.g. ["Li", "Fe", "O"]. compatible_only (bool): Whether to return only "compatible" entries. Compatible entries are entries that have been processed using the MaterialsProject2020Compatibility class, @@ -938,9 +938,9 @@ def query( mongo-style dict. If string, it supports a powerful but simple string criteria. - E.g., "Fe2O3" means search for materials with reduced_formula - Fe2O3. Wild cards are also supported. E.g., "\\*2O" means get - all materials whose formula can be formed as \\*2O, e.g., + e.g. "Fe2O3" means search for materials with reduced_formula + Fe2O3. Wild cards are also supported. e.g. "\\*2O" means get + all materials whose formula can be formed as \\*2O, e.g. Li2O, K2O, etc. Other syntax examples: @@ -973,7 +973,7 @@ def query( Defaults to True. Set to False to reduce visual noise. Returns: - List of results. E.g., + List of results. e.g. [{u'formula': {u'O': 1, u'Li': 2.0}}, {u'formula': {u'Na': 2.0, u'O': 2.0}}, {u'formula': {u'K': 1, u'O': 3.0}}, @@ -1178,7 +1178,7 @@ def submit_vasp_directory( created_at=None, ncpus=None, ): - """Assimilates all vasp run directories beneath a particular + """Assimilate all vasp run directories beneath a particular directory using BorgQueen to obtain structures, and then submits thhem to the Materials Project as SNL files. VASP related meta data like initial structure and final energies are automatically incorporated. @@ -1349,7 +1349,7 @@ def get_surface_data(self, material_id, miller_index=None, inc_structures=False) Args: material_id (str): Materials Project material_id, e.g. 'mp-123'. miller_index (list of integer): The miller index of the surface. - e.g., [3, 2, 1]. If miller_index is provided, only one dictionary + e.g. [3, 2, 1]. If miller_index is provided, only one dictionary of this specific plane will be returned. inc_structures (bool): Include final surface slab structures. These are unnecessary for Wulff shape construction. @@ -1409,12 +1409,12 @@ def get_gb_data( """Get grain boundary data for a material. Args: - material_id (str): Materials Project material_id, e.g., 'mp-129'. - pretty_formula (str): The formula of metals. e.g., 'Fe' - chemsys (str): The chemical system. e.g., 'Fe-O' + material_id (str): Materials Project material_id, e.g. 'mp-129'. + pretty_formula (str): The formula of metals. e.g. 'Fe' + chemsys (str): The chemical system. e.g. 'Fe-O' sigma (int): The sigma value of a certain type of grain boundary - gb_plane (list of integer): The Miller index of grain boundary plane. e.g., [1, 1, 1] - rotation_axis (list of integer): The Miller index of rotation axis. e.g., + gb_plane (list of integer): The Miller index of grain boundary plane. e.g. [1, 1, 1] + rotation_axis (list of integer): The Miller index of rotation axis. e.g. [1, 0, 0], [1, 1, 0], and [1, 1, 1] Sigma value is determined by the combination of rotation axis and rotation angle. The five degrees of freedom (DOF) of one grain boundary include: rotation axis (2 DOFs), rotation angle (1 DOF), and grain boundary plane (2 DOFs). @@ -1578,12 +1578,12 @@ def _check_nomad_exist(url) -> bool: @staticmethod def parse_criteria(criteria_string): - """Parses a powerful and simple string criteria and generates a proper + """Parse a powerful and simple string criteria and generates a proper mongo syntax criteria. Args: criteria_string (str): A string representing a search criteria. - Also supports wild cards. E.g., + Also supports wild cards. e.g. something like "*2O" gets converted to {'pretty_formula': {'$in': [u'B2O', u'Xe2O', u"Li2O", ...]}} @@ -1593,7 +1593,7 @@ def parse_criteria(criteria_string): Li-Fe-O or *-Fe-O: Interpreted as chemical systems. You can mix and match with spaces, which are interpreted as - "OR". E.g., "mp-1234 FeO" means query for all compounds with + "OR". e.g. "mp-1234 FeO" means query for all compounds with reduced formula FeO or with materials_id mp-1234. Returns: diff --git a/pymatgen/ext/optimade.py b/pymatgen/ext/optimade.py index e6a9a589fd9..c462eadd9e0 100644 --- a/pymatgen/ext/optimade.py +++ b/pymatgen/ext/optimade.py @@ -230,7 +230,7 @@ def get_structures( nelements: Number of elements, e.g. 4 or [2, 5] for the range >=2 and <=5 nsites: Number of sites, e.g. 4 or [2, 5] for the range >=2 and <=5 chemical_formula_anonymous: The desired chemical formula in OPTIMADE anonymous formula format - (NB. The ordering is reversed from the pymatgen format, e.g., pymatgen "ABC2" should become "A2BC"). + (NB. The ordering is reversed from the pymatgen format, e.g. pymatgen "ABC2" should become "A2BC"). chemical_formula_hill: The desired chemical formula in the OPTIMADE take on the Hill formula format. (NB. Again, this is different from the pymatgen format, as the OPTIMADE version is a reduced chemical formula simply using the IUPAC/Hill ordering.) @@ -271,7 +271,7 @@ def get_snls( nelements: Number of elements, e.g. 4 or [2, 5] for the range >=2 and <=5 nsites: Number of sites, e.g. 4 or [2, 5] for the range >=2 and <=5 chemical_formula_anonymous: The desired chemical formula in OPTIMADE anonymous formula format - (NB. The ordering is reversed from the pymatgen format, e.g., pymatgen "ABC2" should become "A2BC"). + (NB. The ordering is reversed from the pymatgen format, e.g. pymatgen "ABC2" should become "A2BC"). chemical_formula_hill: The desired chemical formula in the OPTIMADE take on the Hill formula format. (NB. Again, this is different from the pymatgen format, as the OPTIMADE version is a reduced chemical formula simply using the IUPAC/Hill ordering.) @@ -555,7 +555,7 @@ def _handle_response_fields(self, additional_response_fields: str | list[str] | return ",".join({*additional_response_fields, *self.mandatory_response_fields}) def refresh_aliases(self, providers_url="https://providers.optimade.org/providers.json"): - """Updates available OPTIMADE structure resources based on the current list of OPTIMADE + """Update available OPTIMADE structure resources based on the current list of OPTIMADE providers. """ json = self._get_json(providers_url) diff --git a/pymatgen/io/abinit/abiobjects.py b/pymatgen/io/abinit/abiobjects.py index 404cbf853df..79c25c4f782 100644 --- a/pymatgen/io/abinit/abiobjects.py +++ b/pymatgen/io/abinit/abiobjects.py @@ -577,7 +577,7 @@ def __init__( self.algorithm = algorithm @property - def nsppol(self): + def nsppol(self) -> int: """Number of independent spin polarizations.""" return self.spin_mode.nsppol @@ -684,7 +684,7 @@ def __init__( Not used for the other modes kpts: Number of divisions. Even when only a single specification is required, e.g. in the automatic scheme, the kpts should still - be specified as a 2D array. e.g., [[20]] or [[2,2,2]]. + be specified as a 2D array. e.g. [[20]] or [[2,2,2]]. kpt_shifts: Shifts for Kpoints. use_symmetries: False if spatial symmetries should not be used to reduce the number of independent k-points. @@ -937,8 +937,7 @@ def automatic_density( use_time_reversal=True, shifts=(0.5, 0.5, 0.5), ): - """ - Returns an automatic Kpoint object based on a structure and a kpoint + """Get an automatic Kpoint object based on a structure and a kpoint density. Uses Gamma centered meshes for hexagonal cells and Monkhorst-Pack grids otherwise. Algorithm: diff --git a/pymatgen/io/abinit/inputs.py b/pymatgen/io/abinit/inputs.py index 4fd58c59f0d..d6150849b2e 100644 --- a/pymatgen/io/abinit/inputs.py +++ b/pymatgen/io/abinit/inputs.py @@ -130,8 +130,7 @@ def as_structure(obj): @unique class ShiftMode(Enum): - """ - Class defining the mode to be used for the shifts. + """Mode used to generate the shifts for the k-point sampling. G: Gamma centered M: Monkhorst-Pack ((0.5, 0.5, 0.5)) S: Symmetric. Respects the chksymbreak with multiple shifts @@ -146,8 +145,7 @@ class ShiftMode(Enum): @classmethod def from_object(cls, obj) -> Self: - """ - Returns an instance of ShiftMode based on the type of object passed. Converts strings to ShiftMode depending + """Get an instance of ShiftMode based on the type of object passed. Converts strings to ShiftMode depending on the initial letter of the string. G for GammaCentered, M for MonkhorstPack, S for Symmetric, O for OneSymmetric. Case insensitive. @@ -198,19 +196,19 @@ def _find_ecut_pawecutdg(ecut, pawecutdg, pseudos, accuracy): return AttrDict(ecut=ecut, pawecutdg=pawecutdg) -def _find_scf_nband(structure, pseudos, electrons, spinat=None): +def _find_scf_nband(structure, pseudos, electrons: aobj.Electrons, spinat=None): """Find the value of nband.""" if electrons.nband is not None: return electrons.nband - nsppol, smearing = electrons.nsppol, electrons.smearing + n_sp_pol, smearing = electrons.nsppol, electrons.smearing # Number of valence electrons including possible extra charge n_val_elec = num_valence_electrons(structure, pseudos) n_val_elec -= electrons.charge # First guess (semiconductors) - nband = n_val_elec // 2 + n_band = n_val_elec // 2 # TODO: Find better algorithm # If nband is too small we may kill the job, increase nband and restart @@ -218,15 +216,15 @@ def _find_scf_nband(structure, pseudos, electrons, spinat=None): # if the change is not propagated e.g. phonons in metals. # metallic occupation - nband = max(np.ceil(nband * 1.2), nband + 10) if smearing else max(np.ceil(nband * 1.1), nband + 4) + n_band = max(np.ceil(n_band * 1.2), n_band + 10) if smearing else max(np.ceil(n_band * 1.1), n_band + 4) # Increase number of bands based on the starting magnetization - if nsppol == 2 and spinat is not None: - nband += np.ceil(max(np.sum(spinat, axis=0)) / 2.0) + if n_sp_pol == 2 and spinat is not None: + n_band += np.ceil(max(np.sum(spinat, axis=0)) / 2.0) # Force even nband (easier to divide among procs, mandatory if nspinor == 2) - nband += nband % 2 - return int(nband) + n_band += n_band % 2 + return int(n_band) def _get_shifts(shift_mode, structure): diff --git a/pymatgen/io/abinit/netcdf.py b/pymatgen/io/abinit/netcdf.py index dc24724f6d2..5a7a157149c 100644 --- a/pymatgen/io/abinit/netcdf.py +++ b/pymatgen/io/abinit/netcdf.py @@ -132,8 +132,7 @@ def print_tree(self): print(child) def read_dimvalue(self, dimname, path="/", default=NO_DEFAULT): - """ - Returns the value of a dimension. + """Get the value of a dimension. Args: dimname: Name of the variable @@ -157,8 +156,7 @@ def read_varnames(self, path="/"): return list(group.variables) def read_value(self, varname, path="/", cmode=None, default=NO_DEFAULT): - """ - Returns the values of variable with name varname in the group specified by path. + """Get the values of variable with name varname in the group specified by path. Args: varname: Name of the variable diff --git a/pymatgen/io/abinit/pseudos.py b/pymatgen/io/abinit/pseudos.py index 61096e03bce..c10a7d6463d 100644 --- a/pymatgen/io/abinit/pseudos.py +++ b/pymatgen/io/abinit/pseudos.py @@ -316,8 +316,7 @@ def djrepo_path(self): # return None def hint_for_accuracy(self, accuracy="normal"): - """ - Returns a Hint object with the suggested value of ecut [Ha] and + """Get a Hint object with the suggested value of ecut [Ha] and pawecutdg [Ha] for the given accuracy. ecut and pawecutdg are set to zero if no hint is available. diff --git a/pymatgen/io/adf.py b/pymatgen/io/adf.py index fc5f4550664..2677d34420d 100644 --- a/pymatgen/io/adf.py +++ b/pymatgen/io/adf.py @@ -123,11 +123,8 @@ def is_block_key(self) -> bool: return self.name.upper() in self.block_keys @property - def key(self): - """ - Return the name of this key. If this is a block key, the name will be - converted to upper cases. - """ + def key(self) -> str: + """The name of this key. If this is a block key, the name will be converted to upper cases.""" if self.is_block_key(): return self.name.upper() return self.name diff --git a/pymatgen/io/aims/sets/core.py b/pymatgen/io/aims/sets/core.py index 389970abd4e..54e901a00e9 100644 --- a/pymatgen/io/aims/sets/core.py +++ b/pymatgen/io/aims/sets/core.py @@ -42,10 +42,7 @@ def get_parameter_updates(self, structure: Structure | Molecule, prev_parameters @dataclass class RelaxSetGenerator(AimsInputGenerator): - """ - Class to generate FHI-aims relax sets. - - I.e., sets for optimization of internal and lattice coordinates. + """Generate FHI-aims relax sets for optimizing internal coordinates and lattice params. Parameters ---------- diff --git a/pymatgen/io/ase.py b/pymatgen/io/ase.py index 8cc59cb78ca..fce669b38c2 100644 --- a/pymatgen/io/ase.py +++ b/pymatgen/io/ase.py @@ -84,8 +84,7 @@ class AseAtomsAdaptor: @staticmethod def get_atoms(structure: SiteCollection, msonable: bool = True, **kwargs) -> MSONAtoms | Atoms: - """ - Returns ASE Atoms object from pymatgen structure or molecule. + """Get ASE Atoms object from pymatgen structure or molecule. Args: structure (SiteCollection): pymatgen Structure or Molecule @@ -224,8 +223,7 @@ def get_atoms(structure: SiteCollection, msonable: bool = True, **kwargs) -> MSO @staticmethod def get_structure(atoms: Atoms, cls: type[Structure] = Structure, **cls_kwargs) -> Structure: - """ - Returns pymatgen structure from ASE Atoms. + """Get pymatgen structure from ASE Atoms. Args: atoms: ASE Atoms object @@ -354,8 +352,7 @@ def get_structure(atoms: Atoms, cls: type[Structure] = Structure, **cls_kwargs) @staticmethod def get_molecule(atoms: Atoms, cls: type[Molecule] = Molecule, **cls_kwargs) -> Molecule: - """ - Returns pymatgen molecule from ASE Atoms. + """Get pymatgen molecule from ASE Atoms. Args: atoms: ASE Atoms object diff --git a/pymatgen/io/babel.py b/pymatgen/io/babel.py index f6f862bc386..349dd6500fa 100644 --- a/pymatgen/io/babel.py +++ b/pymatgen/io/babel.py @@ -48,8 +48,7 @@ class BabelMolAdaptor: @needs_openbabel def __init__(self, mol: Molecule | openbabel.OBMol | pybel.Molecule) -> None: - """ - Initializes with pymatgen Molecule or OpenBabel's OBMol. + """Initialize with pymatgen Molecule or OpenBabel's OBMol. Args: mol: pymatgen's Molecule/IMolecule or OpenBabel OBMol diff --git a/pymatgen/io/cif.py b/pymatgen/io/cif.py index 6f1ce7e430d..d518c7eba4d 100644 --- a/pymatgen/io/cif.py +++ b/pymatgen/io/cif.py @@ -301,7 +301,7 @@ def __init__( site_tolerance (float): This tolerance is used to determine if two sites are sitting in the same position, in which case they will be combined to a single disordered site. Defaults to 1e-4. frac_tolerance (float): This tolerance is used to determine is a coordinate should be rounded to an ideal - value. E.g., 0.6667 is rounded to 2/3. This is desired if symmetry operations are going to be applied. + value. e.g. 0.6667 is rounded to 2/3. This is desired if symmetry operations are going to be applied. However, for very large CIF files, this may need to be set to 0. check_cif (bool): Whether to check that stoichiometry reported in CIF matches that of resulting Structure, and whether elements are missing. Defaults to True. @@ -571,8 +571,7 @@ def _unique_coords( lattice: Lattice | None = None, labels: dict[Vector3D, str] | None = None, ): - """ - Generate unique coordinates using coord and symmetry positions + """Generate unique coordinates using coord and symmetry positions and also their corresponding magnetic moments, if supplied. """ coords_out: list[np.ndarray] = [] @@ -622,8 +621,7 @@ def get_lattice( angle_strings=("alpha", "beta", "gamma"), lattice_type=None, ): - """ - Generate the lattice from the provided lattice parameters. In + """Generate the lattice from the provided lattice parameters. In the absence of all six lattice parameters, the crystal system and necessary parameters are parsed. """ diff --git a/pymatgen/io/common.py b/pymatgen/io/common.py index ff53c145175..2b4c56ca107 100644 --- a/pymatgen/io/common.py +++ b/pymatgen/io/common.py @@ -83,8 +83,7 @@ def __init__( @property def spin_data(self): - """ - The data decomposed into actual spin data as {spin: data}. + """The data decomposed into actual spin data as {spin: data}. Essentially, this provides the actual Spin.up and Spin.down data instead of the total and diff. Note that by definition, a non-spin-polarized run would have Spin.up data == Spin.down data. @@ -97,8 +96,7 @@ def spin_data(self): return self._spin_data def get_axis_grid(self, ind): - """ - Returns the grid for a particular axis. + """Get the grid for a particular axis. Args: ind (int): Axis index. @@ -210,7 +208,7 @@ def get_integrated_diff(self, ind, radius, nbins=1): Returns: Differential integrated charge as a np array of [[radius, value], - ...]. Format is for ease of plotting. E.g., plt.plot(data[:,0], + ...]. Format is for ease of plotting. e.g. plt.plot(data[:,0], data[:,1]) """ # For non-spin-polarized runs, this is zero by definition. diff --git a/pymatgen/io/core.py b/pymatgen/io/core.py index 898ec149e70..118b14d1924 100644 --- a/pymatgen/io/core.py +++ b/pymatgen/io/core.py @@ -19,7 +19,7 @@ the "recipe", but nothing that is specific to a particular system. get_input_set takes system-specific information (such as structure) and applies the recipe. 3. All InputGenerator must save all supplied args and kwargs as instance variables. - E.g., self.my_arg = my_arg and self.kwargs = kwargs in the __init__. This + e.g. self.my_arg = my_arg and self.kwargs = kwargs in the __init__. This ensures the as_dict and from_dict work correctly. """ @@ -256,8 +256,7 @@ class InputGenerator(MSONable): @abc.abstractmethod def get_input_set(self, *args, **kwargs): - """ - Generate an InputSet object. Typically the first argument to this method + """Generate an InputSet object. Typically the first argument to this method will be a Structure or other form of atomic coordinates. """ raise NotImplementedError(f"get_input_set has not been implemented in {type(self).__name__}") diff --git a/pymatgen/io/cp2k/inputs.py b/pymatgen/io/cp2k/inputs.py index 85145138f55..46ebe635fa3 100644 --- a/pymatgen/io/cp2k/inputs.py +++ b/pymatgen/io/cp2k/inputs.py @@ -61,8 +61,7 @@ class Keyword(MSONable): - """ - Class representing a keyword argument in CP2K. Within CP2K Sections, which activate features + """A keyword argument in CP2K. Within CP2K Sections, which activate features of the CP2K code, the keywords are arguments that control the functionality of that feature. For example, the section "FORCE_EVAL" activates the evaluation of forces/energies, but within "FORCE_EVAL" the keyword "METHOD" controls whether or not this will be done with, say, @@ -78,8 +77,7 @@ def __init__( verbose: bool | None = True, repeats: bool | None = False, ): - """ - Initializes a keyword. These Keywords and the value passed to them are sometimes as simple + """Initialize a keyword. These Keywords and the value passed to them are sometimes as simple as KEYWORD VALUE, but can also be more elaborate such as KEYWORD [UNITS] VALUE1 VALUE2, which is why this class exists: to handle many values and control easy printing to an input file. @@ -192,8 +190,7 @@ class KeywordList(MSONable): """ def __init__(self, keywords: Sequence[Keyword]): - """ - Initializes a keyword list given a sequence of keywords. + """Initialize a keyword list given a sequence of keywords. Args: keywords: A list of keywords. Must all have the same name (case-insensitive) @@ -595,8 +592,7 @@ class SectionList(MSONable): """Section list.""" def __init__(self, sections: Sequence[Section]): - """ - Initializes a SectionList object using a sequence of sections. + """Initialize a SectionList object using a sequence of sections. Args: sections: A list of keywords. Must all have the same name (case-insensitive) @@ -1281,7 +1277,7 @@ def __init__( class Cell(Section): - """Defines the simulation cell (lattice).""" + """Controls the cell/lattice parameters for the simulation.""" def __init__(self, lattice: Lattice, keywords: dict | None = None, **kwargs): """ @@ -1305,7 +1301,7 @@ def __init__(self, lattice: Lattice, keywords: dict | None = None, **kwargs): class Kind(Section): - """Specifies the information for the different atom types being simulated.""" + """Specify the information for the different atom types being simulated.""" def __init__( self, @@ -1445,7 +1441,7 @@ def __init__( class Coord(Section): - """Specifies the coordinates of the atoms using a pymatgen structure object.""" + """Specify the coordinates of the atoms using a pymatgen structure object.""" def __init__( self, @@ -1833,7 +1829,7 @@ def f3(x): class XCFunctional(Section): - """Defines the XC functional(s) to use.""" + """Info about which XC functional to use.""" def __init__( self, @@ -2058,7 +2054,7 @@ def from_kpoints(cls, kpoints: VaspKpoints, structure=None) -> Self: class KpointSet(Section): - """Specifies a kpoint line to be calculated between special points.""" + """Specify a kpoint line to be calculated between special points.""" def __init__(self, npoints: int, kpoints: Iterable, units: str = "B_VECTOR") -> None: """ @@ -2097,7 +2093,7 @@ class Kpoint_Set(KpointSet): class BandStructure(Section): - """Specifies high symmetry paths for outputting the band structure in CP2K.""" + """Specify high symmetry paths for outputting the band structure in CP2K.""" def __init__( self, diff --git a/pymatgen/io/cp2k/outputs.py b/pymatgen/io/cp2k/outputs.py index 2743cde4b54..6902d4604f6 100644 --- a/pymatgen/io/cp2k/outputs.py +++ b/pymatgen/io/cp2k/outputs.py @@ -1493,7 +1493,7 @@ def read_pattern(self, patterns, reverse=False, terminate_on_match=False, postpr arguments. Args: - patterns (dict): A dict of patterns, e.g., + patterns (dict): A dict of patterns, e.g. {"energy": r"energy\\(sigma->0\\)\\s+=\\s+([\\d\\-.]+)"}. reverse (bool): Read files in reverse. Defaults to false. Useful for large files, esp OUTCARs, especially when used with @@ -1645,7 +1645,7 @@ def as_dict(self): # TODO should store as pandas? Maybe it should be stored as a dict so it's python native def parse_energy_file(energy_file): - """Parses energy file for calculations with multiple ionic steps.""" + """Parse energy file for calculations with multiple ionic steps.""" columns = [ "step", "kinetic_energy", diff --git a/pymatgen/io/feff/inputs.py b/pymatgen/io/feff/inputs.py index 3be8f2b05e3..6ca04d8d87c 100644 --- a/pymatgen/io/feff/inputs.py +++ b/pymatgen/io/feff/inputs.py @@ -216,13 +216,8 @@ def from_cif_file(cls, cif_file: str, source: str = "", comment: str = "") -> Se return cls(structure, source, comment) @property - def structure_symmetry(self): - """ - Returns space number and space group. - - Returns: - Space number and space group list - """ + def structure_symmetry(self) -> tuple[str, int]: + """The space group symbol and space number of the structure.""" return self.space_group, self.space_number @property @@ -477,8 +472,7 @@ def cluster_from_file(filename): return Molecule(symbols, coords) def get_lines(self) -> list[list[str | int]]: - """ - Returns a list of string representations of the atomic configuration + """Get a list of string representations of the atomic configuration information(x, y, z, ipot, atom_symbol, distance, id). Returns: @@ -580,8 +574,7 @@ def from_dict(cls, dct: dict) -> Self: return cls({k: v for k, v in dct.items() if k not in ("@module", "@class")}) def get_str(self, sort_keys: bool = False, pretty: bool = False) -> str: - """ - Returns a string representation of the Tags. The reason why this + """Get a string representation of the Tags. The reason why this method is different from the __str__ method is to provide options for pretty printing. @@ -880,8 +873,7 @@ def pot_dict_from_str(pot_data): return pot_dict, pot_dict_reverse def __str__(self): - """ - Returns a string representation of potential parameters to be used in + """Get a string representation of potential parameters to be used in the feff.inp file, determined from structure object. @@ -974,7 +966,7 @@ def write_file(self, filename="paths.dat"): class FeffParseError(ParseError): """Exception class for Structure. - Raised when the structure has problems, e.g., atoms that are too close. + Raised when the structure has problems, e.g. atoms that are too close. """ diff --git a/pymatgen/io/feff/outputs.py b/pymatgen/io/feff/outputs.py index c8e32cfa805..2d8bb9eeba4 100644 --- a/pymatgen/io/feff/outputs.py +++ b/pymatgen/io/feff/outputs.py @@ -258,14 +258,14 @@ class Xmu(MSONable): r""" Parser for data in 'xmu.dat' file. The file 'xmu.dat' contains XANES, EXAFS or NRIXS data depending on the - situation; \\mu, \\mu_0, and \\chi = \\chi * \\mu_0/ \\mu_0/(edge+50eV) as + situation; \mu, \mu_0, and \chi = \chi * \mu_0 / \mu_0 / (edge+50eV) as functions of absolute energy E, relative energy E - E_f and wave number k. Default attributes: xmu: Photon absorption cross section of absorbing atom in material Energies: Energies of data point relative_energies: E - E_fermi - wavenumber: k=\\sqrt(E -E_fermi) + wavenumber: k=\sqrt(E -E_fermi) mu: The total absorption cross-section. mu0: The embedded atomic background absorption. chi: fine structure. @@ -317,16 +317,12 @@ def energies(self): @property def relative_energies(self): - """ - Returns energy with respect to the Fermi level. - E - E_f. - """ + """Energy with respect to the Fermi level E - E_f.""" return self.data[:, 1] @property def wavenumber(self): - r""" - Returns The wave number in units of \\AA^-1. k=\\sqrt(E - E_f) where E is + r"""Get the wave number in units of \AA^-1. k=\sqrt(E - E_f) where E is the energy and E_f is the Fermi level computed from electron gas theory at the average interstitial charge density. """ diff --git a/pymatgen/io/feff/sets.py b/pymatgen/io/feff/sets.py index 8310fc9fe3d..e7f306b8775 100644 --- a/pymatgen/io/feff/sets.py +++ b/pymatgen/io/feff/sets.py @@ -59,8 +59,7 @@ def header(self): @property @abc.abstractmethod def atoms(self): - """ - Returns Atoms string from a structure that goes in feff.inp file. + """Get Atoms string from a structure that goes in feff.inp file. Returns: Atoms object. @@ -163,7 +162,7 @@ def __init__( being written to the input file. spacegroup_analyzer_settings (dict): parameters passed to SpacegroupAnalyzer. - E.g., {"symprec": 0.01, "angle_tolerance": 4} + e.g. {"symprec": 0.01, "angle_tolerance": 4} """ self.absorbing_atom = absorbing_atom self.user_tag_settings = user_tag_settings or {} diff --git a/pymatgen/io/gaussian.py b/pymatgen/io/gaussian.py index 994ce3c7a6d..bbb47501699 100644 --- a/pymatgen/io/gaussian.py +++ b/pymatgen/io/gaussian.py @@ -123,8 +123,8 @@ def __init__( route_parameters: Additional route parameters as a dict. For example, {'SP':"", "SCF":"Tight"} input_parameters: Additional input parameters for run as a dict. Used - for example, in PCM calculations. E.g., {"EPS":12} - link0_parameters: Link0 parameters as a dict. E.g., {"%mem": "1000MW"} + for example, in PCM calculations. e.g. {"EPS":12} + link0_parameters: Link0 parameters as a dict. e.g. {"%mem": "1000MW"} dieze_tag: # preceding the route line. E.g. "#p" gen_basis: allows a user-specified basis set to be used in a Gaussian calculation. If this is not None, the attribute ``basis_set`` will @@ -260,7 +260,7 @@ def _parse_coords(coord_lines): def _parse_species(sp_str): """ - The species specification can take many forms. E.g., + The species specification can take many forms. e.g. simple integers representing atomic numbers ("8"), actual species string ("C") or a labelled species ("C1"). Sometimes, the species string is also not properly capitalized, @@ -528,7 +528,7 @@ class GaussianOutput: route (dict): Additional route parameters as a dict. For example, {'SP':"", "SCF":"Tight"}. dieze_tag (str): # preceding the route line, e.g. "#P". - link0 (dict): Link0 parameters as a dict. E.g., {"%mem": "1000MW"}. + link0 (dict): Link0 parameters as a dict. e.g. {"%mem": "1000MW"}. charge (int): Charge for structure. spin_multiplicity (int): Spin multiplicity for structure. num_basis_func (int): Number of basis functions in the run. diff --git a/pymatgen/io/icet.py b/pymatgen/io/icet.py index 4eb40f45c20..da63c89e040 100644 --- a/pymatgen/io/icet.py +++ b/pymatgen/io/icet.py @@ -179,7 +179,7 @@ def _get_site_composition(self) -> None: 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} @@ -223,8 +223,7 @@ def get_icet_sqs_obj(self, material: Atoms | Structure, cluster_space: _ClusterS ) def enumerate_sqs_structures(self, cluster_space: _ClusterSpace | None = None) -> list: - """ - Generate an SQS by enumeration of all possible arrangements. + """Generate an SQS by enumeration of all possible arrangements. Adapted from icet.tools.structure_generation.generate_sqs_by_enumeration to accommodate multiprocessing. diff --git a/pymatgen/io/jarvis.py b/pymatgen/io/jarvis.py index 2ace4819445..b1cc2938a53 100644 --- a/pymatgen/io/jarvis.py +++ b/pymatgen/io/jarvis.py @@ -18,8 +18,7 @@ class JarvisAtomsAdaptor: @staticmethod def get_atoms(structure): - """ - Returns JARVIS Atoms object from pymatgen structure. + """Get JARVIS Atoms object from pymatgen structure. Args: structure: pymatgen Structure @@ -42,8 +41,7 @@ def get_atoms(structure): @staticmethod def get_structure(atoms): - """ - Returns pymatgen structure from JARVIS Atoms. + """Get pymatgen structure from JARVIS Atoms. Args: atoms: JARVIS Atoms object diff --git a/pymatgen/io/lammps/data.py b/pymatgen/io/lammps/data.py index 154f63c1b58..a31c38dfbb7 100644 --- a/pymatgen/io/lammps/data.py +++ b/pymatgen/io/lammps/data.py @@ -153,8 +153,7 @@ def volume(self) -> float: return np.dot(np.cross(matrix[0], matrix[1]), matrix[2]) def get_str(self, significant_figures: int = 6) -> str: - """ - Returns the string representation of simulation box in LAMMPS + """Get the string representation of simulation box in LAMMPS data file format. Args: @@ -323,8 +322,7 @@ def structure(self) -> Structure: ) def get_str(self, distance: int = 6, velocity: int = 8, charge: int = 4, hybrid: bool = True) -> str: - """ - Returns the string representation of LammpsData, essentially + """Get the string representation of LammpsData, essentially the string to be written to a file. Support hybrid style coeffs read and write. @@ -863,7 +861,7 @@ def set_charge_atom(self, charges: dict[int, float]) -> None: Args: charges: A dictionary with atom indexes as keys and - charges as values, e.g., to set the charge + charges as values, e.g. to set the charge of the atom with index 3 to -2, use `{3: -2}`. """ for iat, q in charges.items(): @@ -888,8 +886,7 @@ def set_charge_atom_type(self, charges: dict[str | int, float]) -> None: class Topology(MSONable): - """ - Class carrying most data in Atoms, Velocities and molecular topology sections for + """Class carrying most data in Atoms, Velocities and molecular topology sections for ONE SINGLE Molecule or Structure object, or a plain list of Sites. """ @@ -973,7 +970,7 @@ def from_bonding( Another constructor that creates an instance from a molecule. Covalent bonds and other bond-based topologies (angles and dihedrals) can be automatically determined. Cannot be used for - non bond-based topologies, e.g., improper dihedrals. + non bond-based topologies, e.g. improper dihedrals. Args: molecule (Molecule): Input molecule. @@ -1024,10 +1021,10 @@ def from_bonding( class ForceField(MSONable): """ - Class carrying most data in Masses and force field sections. + Class carrying most data in masses and force field sections. Attributes: - masses (pandas.DataFrame): DataFrame for Masses section. + masses (pandas.DataFrame): DataFrame for masses section. force_fieldct (dict): Force field section keywords (keys) and data (values) as DataFrames. maps (dict): Dict for labeling atoms and topologies. @@ -1460,8 +1457,7 @@ def from_lammpsdata( return cls(mols, names, list_of_numbers, coordinates, style_return) def get_str(self, distance: int = 6, velocity: int = 8, charge: int = 4, hybrid: bool = True) -> str: - """ - Returns the string representation of CombinedData, essentially + """Get the string representation of CombinedData, essentially the string to be written to a file. Combination info is included as a comment. For single molecule ID data, the info format is: num name diff --git a/pymatgen/io/lammps/generators.py b/pymatgen/io/lammps/generators.py index baa74a24963..f9ca7f73573 100644 --- a/pymatgen/io/lammps/generators.py +++ b/pymatgen/io/lammps/generators.py @@ -36,11 +36,11 @@ class BaseLammpsGenerator(InputGenerator): r""" Base class to generate LAMMPS input sets. Uses template files for the input. The variables that can be changed - in the input template file are those starting with a $ sign, e.g., $nsteps. + in the input template file are those starting with a $ sign, e.g. $nsteps. This generic class is specialized for each template in subclasses, e.g. LammpsMinimization. You can create a template for your own task following those present in pymatgen/io/lammps/templates. The parameters are then replaced based on the values found - in the settings dictionary that you provide, e.g., `{"nsteps": 1000}`. + in the settings dictionary that you provide, e.g. `{"nsteps": 1000}`. Attributes: template: Path (string) to the template file used to create the InputFile for LAMMPS. diff --git a/pymatgen/io/lammps/inputs.py b/pymatgen/io/lammps/inputs.py index f85d968765c..b5b526e404a 100644 --- a/pymatgen/io/lammps/inputs.py +++ b/pymatgen/io/lammps/inputs.py @@ -44,8 +44,7 @@ class LammpsInputFile(InputFile): - """ - Class representing a LAMMPS input settings file, e.g. in.lammps. + """LAMMPS input settings file such as `in.lammps`. Allows for LAMMPS input generation in line/stage wise manner. A stage here is defined as a block of LAMMPS input commands usually performing a specific task during the simulation such as energy minimization or @@ -95,8 +94,7 @@ def nstages(self) -> int: @property def ncomments(self) -> int: - """ - Returns the number of comments in the current LammpsInputFile. Includes the blocks of comments as well + """Get the number of comments in the current LammpsInputFile. Includes the blocks of comments as well as inline comments (comment lines within blocks of LAMMPS commands). """ n_comments = 0 @@ -137,8 +135,7 @@ def get_args(self, command: str, stage_name: str | None = None) -> list | str: return args if len(args) != 1 else args[0] def contains_command(self, command: str, stage_name: str | None = None) -> bool: - """ - Returns whether a given command is present in the LammpsInputFile. + """Get whether a given command is present in the LammpsInputFile. A stage name can be given; in this case the search will happen only for this stage. Args: @@ -161,8 +158,8 @@ def set_args( either the first occurrence, all of them, or the index of the occurrence. Args: - command (str): String representing the command to change, e.g., "units". - argument (str): String with the new value for the command, e.g., "atomic". + command (str): String representing the command to change, e.g. "units". + argument (str): String with the new value for the command, e.g. "atomic". stage_name (str): String giving the stage name where the change should take place. how (str or int or list): "all" for changing all occurrences of the command within the stage_name or the whole InputFile, "first" for the first occurrence, int i for the i-th time the command @@ -374,7 +371,7 @@ def add_commands(self, stage_name: str, commands: str | list[str] | dict) -> Non commands="pair_coeff 1 1 morse 0.0580 3.987 3.404" ) ``` - To add multiple commands, use a dict or a list, e.g., + To add multiple commands, use a dict or a list, e.g. ``` your_input_file.add_commands( stage_name="Definition of the potential", @@ -485,8 +482,7 @@ def append(self, lmp_input_file: LammpsInputFile) -> None: self.stages += new_list_to_add def get_str(self, ignore_comments: bool = False, keep_stages: bool = True) -> str: - """ - Generates and ² the string representation of the LammpsInputFile. + """Generate and ² the string representation of the LammpsInputFile. Stages are separated by empty lines. The headers of the stages will be put in comments preceding each stage. Other comments will be put inline within stages, where they have been added. @@ -864,9 +860,9 @@ def __init__(self, script_template: str, settings: dict, data: LammpsData | str, Args: script_template (str): String template for input script with placeholders. The format for placeholders has to - be '$variable_name', e.g., '$temperature' + be '$variable_name', e.g. '$temperature' settings (dict): Contains values to be written to the - placeholders, e.g., {'temperature': 1}. + placeholders, e.g. {'temperature': 1}. data (LammpsData or str): Data file as a LammpsData instance or path to an existing data file. Default to None, i.e., no data file supplied. Useful only when @@ -957,9 +953,9 @@ def get_input_set( # type: ignore Args: script_template: String template for input script with placeholders. The format for placeholders has to be - '$variable_name', e.g., '$temperature' + '$variable_name', e.g. '$temperature' settings: Contains values to be written to the - placeholders, e.g., {'temperature': 1}. Default to None. + placeholders, e.g. {'temperature': 1}. Default to None. data: Data file as a LammpsData instance. Default to None, i.e., no data file supplied. Note that a matching 'read_data' command must be provided in the script template in order for the data @@ -996,9 +992,9 @@ def write_lammps_inputs( output_dir (str): Directory to output the input files. script_template (str): String template for input script with placeholders. The format for placeholders has to be - '$variable_name', e.g., '$temperature' + '$variable_name', e.g. '$temperature' settings (dict): Contains values to be written to the - placeholders, e.g., {'temperature': 1}. Default to None. + placeholders, e.g. {'temperature': 1}. Default to None. data (LammpsData or str): Data file as a LammpsData instance or path to an existing data file. Default to None, i.e., no data file supplied. Useful only when read_data cmd is in diff --git a/pymatgen/io/lmto.py b/pymatgen/io/lmto.py index a5213644fae..3ec52d344f6 100644 --- a/pymatgen/io/lmto.py +++ b/pymatgen/io/lmto.py @@ -62,8 +62,7 @@ def __str__(self): return self.get_str() def get_str(self, sigfigs=8) -> str: - """ - Generates the string representation of the CTRL file. This is + """Generate the string representation of the CTRL file. This is the minimal CTRL file necessary to execute lmhart.run. """ ctrl_dict = self.as_dict() @@ -91,8 +90,7 @@ def get_str(self, sigfigs=8) -> str: return "\n".join(lines) + "\n" def as_dict(self): - """ - Returns the CTRL as a dictionary. "SITE" and "CLASS" are of + """Get the CTRL as a dictionary. "SITE" and "CLASS" are of the form {'CATEGORY': {'TOKEN': value}}, the rest is of the form 'TOKEN'/'CATEGORY': value. It gets the conventional standard structure because primitive cells use the conventional diff --git a/pymatgen/io/lobster/inputs.py b/pymatgen/io/lobster/inputs.py index 21c13938295..500d7fd83e4 100644 --- a/pymatgen/io/lobster/inputs.py +++ b/pymatgen/io/lobster/inputs.py @@ -815,10 +815,9 @@ def standard_calculations_from_vasp_files( def get_all_possible_basis_combinations(min_basis: list, max_basis: list) -> list: """ - Args: - min_basis: list of basis entries: e.g., ['Si 3p 3s '] - max_basis: list of basis entries: e.g., ['Si 3p 3s ']. + min_basis: list of basis entries: e.g. ['Si 3p 3s '] + max_basis: list of basis entries: e.g. ['Si 3p 3s ']. Returns: list[list[str]]: all possible combinations of basis functions, e.g. [['Si 3p 3s']] diff --git a/pymatgen/io/lobster/lobsterenv.py b/pymatgen/io/lobster/lobsterenv.py index 72b22500494..69afc967327 100644 --- a/pymatgen/io/lobster/lobsterenv.py +++ b/pymatgen/io/lobster/lobsterenv.py @@ -35,6 +35,7 @@ from typing_extensions import Self from pymatgen.core import Structure + from pymatgen.core.periodic_table import Element __author__ = "Janine George" __copyright__ = "Copyright 2021, The Materials Project" @@ -114,9 +115,9 @@ def __init__( filename_blist_sg1: (str) Path to additional ICOOP, ICOBI data for structure graphs filename_blist_sg2: (str) Path to additional ICOOP, ICOBI data for structure graphs id_blist_sg1: (str) Identity of data in filename_blist_sg1, - e.g., "icoop" or "icobi" + e.g. "icoop" or "icobi" id_blist_sg2: (str) Identity of data in filename_blist_sg2, - e.g., "icoop" or "icobi". + e.g. "icoop" or "icobi". """ if filename_icohp is not None: self.ICOHP = Icohplist(are_coops=are_coops, are_cobis=are_cobis, filename=filename_icohp) @@ -222,19 +223,18 @@ def __init__( ) @property - def structures_allowed(self): + def structures_allowed(self) -> bool: """Whether this NearNeighbors class can be used with Structure objects?""" return True @property - def molecules_allowed(self): + def molecules_allowed(self) -> bool: """Whether this NearNeighbors class can be used with Molecule objects?""" return False @property - def anion_types(self): - """ - Return the types of anions present in crystal structure as a set + def anion_types(self) -> set[Element]: + """The types of anions present in crystal structure as a set. Returns: set[Element]: describing anions in the crystal structure. @@ -1414,7 +1414,7 @@ class ICOHPNeighborsInfo(NamedTuple): n_bonds (int): number of identified bonds to the selected sites labels (list[str]): labels (from ICOHPLIST) for all identified bonds atoms (list[list[str]]): list of list describing the species present in the identified interactions - (names from ICOHPLIST), e.g., ["Ag3", "O5"] + (names from ICOHPLIST), e.g. ["Ag3", "O5"] central_isites (list[int]): list of the central isite for each identified interaction. """ diff --git a/pymatgen/io/lobster/outputs.py b/pymatgen/io/lobster/outputs.py index 1c0a7480c0b..acc6ccf1390 100644 --- a/pymatgen/io/lobster/outputs.py +++ b/pymatgen/io/lobster/outputs.py @@ -50,8 +50,7 @@ class Cohpcar: - """ - Class to read COHPCAR/COOPCAR/COBICAR files generated by LOBSTER. + """Read COHPCAR/COOPCAR/COBICAR files generated by LOBSTER. Attributes: cohp_data (dict[str, Dict[str, Any]]): A dictionary containing the COHP data of the form: @@ -324,8 +323,7 @@ def _get_bond_data(line: str, are_multi_center_cobis: bool = False) -> dict: class Icohplist(MSONable): - """ - Class to read ICOHPLIST/ICOOPLIST files generated by LOBSTER. + """Read ICOHPLIST/ICOOPLIST files generated by LOBSTER. Attributes: are_coops (bool): Indicates whether the object is consisting of COOPs. @@ -527,15 +525,14 @@ def icohpcollection(self): class NciCobiList: - """ - Class to read NcICOBILIST (multi-center ICOBI) files generated by LOBSTER. + """Read NcICOBILIST (multi-center ICOBI) files generated by LOBSTER. Attributes: is_spin_polarized (bool): Boolean to indicate if the calculation is spin polarized. NciCobiList (dict): Dict containing the listfile data of the form: {bond: "number_of_atoms": number of atoms involved in the multi-center interaction, - "ncicobi": {Spin.up: Nc-ICOBI(Ef) spin up, Spin.down: ...}}, - "interaction_type": type of the multi-center interaction + "ncicobi": {Spin.up: Nc-ICOBI(Ef) spin up, Spin.down: ...}}, + "interaction_type": type of the multi-center interaction """ def __init__(self, filename: str | None = "NcICOBILIST.lobster"): # LOBSTER < 4.1.0: no COBI/ICOBI/NcICOBI @@ -627,8 +624,7 @@ def ncicobi_list(self) -> dict[Any, dict[str, Any]]: class Doscar: - """ - Class to deal with Lobster's projected DOS and local projected DOS. + """Deal with Lobster's projected DOS and local projected DOS. The beforehand quantum-chemical calculation was performed with VASP. Attributes: @@ -780,8 +776,7 @@ def is_spin_polarized(self) -> bool: class Charge(MSONable): - """ - Class to read CHARGE files generated by LOBSTER. + """Read CHARGE files generated by LOBSTER. Attributes: atomlist (list[str]): List of atoms in CHARGE.lobster. @@ -857,8 +852,7 @@ def Loewdin(self): class Lobsterout(MSONable): - """ - Class to read in the lobsterout and evaluate the spilling, save the basis, save warnings, save infos. + """Read in the lobsterout and evaluate the spilling, save the basis, save warnings, save infos. Attributes: basis_functions (list[str]): List of basis functions that were used in lobster run as strings. @@ -1426,8 +1420,7 @@ def get_bandstructure(self): class Bandoverlaps(MSONable): - """ - Class to read in bandOverlaps.lobster files. These files are not created during every Lobster run. + """Read in bandOverlaps.lobster files. These files are not created during every Lobster run. Attributes: band_overlaps_dict (dict[Spin, Dict[str, Dict[str, Union[float, np.ndarray]]]]): A dictionary containing the band overlap data of the form: {spin: {"kpoint as string": {"maxDeviation": @@ -1579,8 +1572,7 @@ def bandoverlapsdict(self): class Grosspop(MSONable): - """ - Class to read in GROSSPOP.lobster files. + """Read in GROSSPOP.lobster files. Attributes: list_dict_grosspop (list[dict[str, str| dict[str, str]]]): List of dictionaries @@ -1647,8 +1639,7 @@ def get_structure_with_total_grosspop(self, structure_filename: str) -> Structur class Wavefunction: - """ - Class to read in wave function files from Lobster and transfer them into an object of the type VolumetricData. + """Read in wave function files from Lobster and transfer them into an object of the type VolumetricData. Attributes: grid (tuple[int, int, int]): Grid for the wave function [Nx+1,Ny+1,Nz+1]. @@ -1788,7 +1779,7 @@ def write_file(self, filename="WAVECAR.vasp", part="real"): or similar (the whole unit cell has to be covered!). Args: - filename: Filename for the output, e.g., WAVECAR.vasp + filename: Filename for the output, e.g. WAVECAR.vasp part: which part of the wavefunction will be saved ("real" or "imaginary") """ if not ( @@ -1809,8 +1800,7 @@ def write_file(self, filename="WAVECAR.vasp", part="real"): # madelung and site potential classes class MadelungEnergies(MSONable): - """ - Class to read MadelungEnergies.lobster files generated by LOBSTER. + """Read MadelungEnergies.lobster files generated by LOBSTER. Attributes: madelungenergies_mulliken (float): Float that gives the Madelung energy based on the Mulliken approach. @@ -1865,8 +1855,7 @@ def madelungenergies_Mulliken(self): class SitePotential(MSONable): - """ - Class to read SitePotentials.lobster files generated by LOBSTER. + """Read SitePotentials.lobster files generated by LOBSTER. Attributes: atomlist (list[str]): List of atoms in SitePotentials.lobster. @@ -1992,7 +1981,6 @@ def madelungenergies_Loewdin(self): def get_orb_from_str(orbs): """ - Args: orbs: list of two or more str, e.g. ["2p_x", "3s"]. @@ -2031,8 +2019,7 @@ def get_orb_from_str(orbs): class LobsterMatrices: - """ - Class to read Matrices file generated by LOBSTER (e.g. hamiltonMatrices.lobster). + """Read Matrices file generated by LOBSTER (e.g. hamiltonMatrices.lobster). Attributes: for filename == "hamiltonMatrices.lobster" diff --git a/pymatgen/io/nwchem.py b/pymatgen/io/nwchem.py index e902534c8de..c7382876c2a 100644 --- a/pymatgen/io/nwchem.py +++ b/pymatgen/io/nwchem.py @@ -108,7 +108,7 @@ def __init__( which means that the spin multiplicity is set to 1 if the molecule has no unpaired electrons and to 2 if there are unpaired electrons. - basis_set: The basis set used for the task as a dict. E.g., + basis_set: The basis set used for the task as a dict. e.g. {"C": "6-311++G**", "H": "6-31++G**"}. basis_set_option: cartesian (default) | spherical, title: Title for the task. Defaults to None, which means a title @@ -251,7 +251,7 @@ def from_molecule( which means that the spin multiplicity is set to 1 if the molecule has no unpaired electrons and to 2 if there are unpaired electrons. - basis_set: The basis set to be used as string or a dict. E.g., + basis_set: The basis set to be used as string or a dict. e.g. {"C": "6-311++G**", "H": "6-31++G**"} or "6-31G". If string, same basis set is used for all elements. basis_set_option: cartesian (default) | spherical, @@ -347,10 +347,10 @@ def __init__( direct input to the geometry section of the Gaussian input file. tasks: List of NwTasks. - directives: List of root level directives as tuple. E.g., + directives: List of root level directives as tuple. e.g. [("start", "water"), ("print", "high")] geometry_options: Additional list of options to be supplied to the - geometry. E.g., ["units", "angstroms", "noautoz"]. Defaults to + geometry. e.g. ["units", "angstroms", "noautoz"]. Defaults to ("units", "angstroms"). symmetry_options: Addition list of option to be supplied to the symmetry. E.g. ["c1"] to turn off the symmetry @@ -621,8 +621,7 @@ def parse_tddft(self): return roots def get_excitation_spectrum(self, width=0.1, npoints=2000): - """ - Generate an excitation spectra from the singlet roots of TDDFT calculations. + """Generate an excitation spectra from the singlet roots of TDDFT calculations. Args: width (float): Width for Gaussian smearing. diff --git a/pymatgen/io/packmol.py b/pymatgen/io/packmol.py index 7bd24d85df1..70cce25c10e 100644 --- a/pymatgen/io/packmol.py +++ b/pymatgen/io/packmol.py @@ -137,8 +137,7 @@ def get_input_set( # type: ignore molecules: list[dict], box: list[float] | None = None, ) -> PackmolSet: - """ - Generate a Packmol InputSet for a set of molecules. + """Generate a Packmol InputSet for a set of molecules. Args: molecules: A list of dict containing information about molecules to pack diff --git a/pymatgen/io/prismatic.py b/pymatgen/io/prismatic.py index 80b9ae02cfd..58685a06a39 100644 --- a/pymatgen/io/prismatic.py +++ b/pymatgen/io/prismatic.py @@ -9,8 +9,7 @@ class Prismatic: - """ - Class to write Prismatic (http://prism-em.com/) input files. + """Write Prismatic (http://prism-em.com) input files. This is designed for STEM image simulation. """ diff --git a/pymatgen/io/pwmat/outputs.py b/pymatgen/io/pwmat/outputs.py index cc979c5818a..293c2d443c7 100644 --- a/pymatgen/io/pwmat/outputs.py +++ b/pymatgen/io/pwmat/outputs.py @@ -101,8 +101,7 @@ def atom_forces(self) -> np.ndarray: @property def e_atoms(self) -> np.ndarray: - """ - Returns individual energies of atoms in each ionic step structures + """Get individual energies of atoms in each ionic step structures contained in MOVEMENT. Returns: diff --git a/pymatgen/io/pwscf.py b/pymatgen/io/pwscf.py index a045e77def7..9c2a2401c2f 100644 --- a/pymatgen/io/pwscf.py +++ b/pymatgen/io/pwscf.py @@ -37,8 +37,7 @@ def __init__( kpoints_grid=(1, 1, 1), kpoints_shift=(0, 0, 0), ): - """ - Initializes a PWSCF input file. + """Initialize a PWSCF input file. Args: structure (Structure): Input structure. For spin-polarized calculation, @@ -357,7 +356,7 @@ def input_mode(line): @staticmethod def proc_val(key, val): - """Static helper method to convert PWINPUT parameters to proper type, e.g., + """Static helper method to convert PWINPUT parameters to proper type, e.g. integers, floats, etc. Args: @@ -537,7 +536,7 @@ def read_pattern(self, patterns, reverse=False, terminate_on_match=False, postpr arguments. Args: - patterns (dict): A dict of patterns, e.g., + patterns (dict): A dict of patterns, e.g. {"energy": r"energy\\(sigma->0\\)\\s+=\\s+([\\d\\-.]+)"}. reverse (bool): Read files in reverse. Defaults to false. Useful for large files, esp OUTCARs, especially when used with diff --git a/pymatgen/io/qchem/outputs.py b/pymatgen/io/qchem/outputs.py index 9d61aa1039e..f1865a79e59 100644 --- a/pymatgen/io/qchem/outputs.py +++ b/pymatgen/io/qchem/outputs.py @@ -684,7 +684,7 @@ def _read_eigenvalues(self): self.data["alpha_eigenvalues"] = alpha_eigenvalues def _read_fock_matrix(self): - """Parses the Fock matrix. The matrix is read in whole + """Parse the Fock matrix. The matrix is read in whole from the output file and then transformed into the right dimensions. """ # The header is the same for both spin-restricted and spin-unrestricted calculations. @@ -723,7 +723,7 @@ def _read_fock_matrix(self): self.data["beta_fock_matrix"] = beta_fock_matrix def _read_coefficient_matrix(self): - """Parses the coefficient matrix from the output file. Done is much + """Parse the coefficient matrix from the output file. Done is much the same was as the Fock matrix. """ # The header is the same for both spin-restricted and spin-unrestricted calculations. @@ -761,7 +761,7 @@ def _read_coefficient_matrix(self): self.data["beta_coeff_matrix"] = beta_coeff_matrix def _read_charge_and_multiplicity(self): - """Parses charge and multiplicity.""" + """Parse charge and multiplicity.""" temp_charge = read_pattern(self.text, {"key": r"\$molecule\s+([\-\d]+)\s+\d"}, terminate_on_match=True).get( "key" ) @@ -795,7 +795,7 @@ def _read_charge_and_multiplicity(self): self.data["multiplicity"] = int(float(temp_multiplicity[0][0])) + 1 def _read_species_and_inital_geometry(self): - """Parses species and initial geometry.""" + """Parse species and initial geometry.""" header_pattern = r"Standard Nuclear Orientation \(Angstroms\)\s+I\s+Atom\s+X\s+Y\s+Z\s+-+" table_pattern = r"\s*\d+\s+([a-zA-Z]+)\s*([\d\-\.]+)\s*([\d\-\.]+)\s*([\d\-\.]+)\s*" footer_pattern = r"\s*-+" @@ -837,7 +837,7 @@ def _read_species_and_inital_geometry(self): self.data["initial_molecule"] = None def _read_SCF(self): - """Parses both old and new SCFs.""" + """Parse both old and new SCFs.""" if self.data.get("using_GEN_SCFMAN", []): footer_pattern = r"(^\s*\-+\n\s+SCF time|^\s*gen_scfman_exception: SCF failed to converge)" header_pattern = ( @@ -1238,7 +1238,7 @@ def _detect_general_warnings(self): self.data["warnings"]["diagonalizing_BBt"] = True def _read_geometries(self): - """Parses all geometries from an optimization trajectory.""" + """Parse all geometries from an optimization trajectory.""" geoms = [] if self.data.get("new_optimizer") is None: header_pattern = r"\s+Optimization\sCycle:\s+\d+\s+Coordinates \(Angstroms\)\s+ATOM\s+X\s+Y\s+Z" @@ -1348,7 +1348,7 @@ def _get_grad_format_length(self, header): return index - 2 def _read_gradients(self): - """Parses all gradients obtained during an optimization trajectory.""" + """Parse all gradients obtained during an optimization trajectory.""" grad_header_pattern = r"Gradient of (?:SCF)?(?:MP2)? Energy(?: \(in au\.\))?" footer_pattern = r"(?:Max gradient component|Gradient time)" @@ -1479,7 +1479,7 @@ def _read_optimization_data(self): self.data["errors"] += ["svd_failed"] def _read_frequency_data(self): - """Parses cpscf_nseg, frequencies, enthalpy, entropy, and mode vectors.""" + """Parse cpscf_nseg, frequencies, enthalpy, entropy, and mode vectors.""" if read_pattern(self.text, {"key": r"Calculating MO derivatives via CPSCF"}, terminate_on_match=True).get( "key" ) == [[]]: @@ -1766,7 +1766,7 @@ def _read_scan_data(self): ) def _read_pcm_information(self): - """Parses information from PCM solvent calculations.""" + """Parse information from PCM solvent calculations.""" temp_dict = read_pattern( self.text, { @@ -1791,7 +1791,7 @@ def _read_pcm_information(self): self.data["solvent_data"][key] = temp_result def _read_smd_information(self): - """Parses information from SMD solvent calculations.""" + """Parse information from SMD solvent calculations.""" temp_dict = read_pattern( self.text, { @@ -1908,7 +1908,7 @@ def _read_cmirs_information(self): self.data["solvent_data"]["cmirs"][key] = temp_result def _read_nbo_data(self): - """Parses NBO output.""" + """Parse NBO output.""" dfs = nbo_parser(self.filename) nbo_data = {} for key, value in dfs.items(): @@ -1916,7 +1916,7 @@ def _read_nbo_data(self): self.data["nbo_data"] = nbo_data def _read_cdft(self): - """Parses output from charge- or spin-constrained DFT (CDFT) calculations.""" + """Parse output from charge- or spin-constrained DFT (CDFT) calculations.""" # Parse constraint and optimization parameters temp_dict = read_pattern( self.text, {"constraint": r"Constraint\s+(\d+)\s+:\s+([\-\.0-9]+)", "multiplier": r"\s*Lam\s+([\.\-0-9]+)"} @@ -2055,7 +2055,7 @@ def _read_almo_msdft(self): self.data["almo_coupling_eV"] = float(temp_dict["coupling"][0][0]) / 1000 def _check_completion_errors(self): - """Parses potential errors that can cause jobs to crash.""" + """Parse potential errors that can cause jobs to crash.""" if read_pattern( self.text, {"key": r"Coordinates do not transform within specified threshold"}, diff --git a/pymatgen/io/qchem/utils.py b/pymatgen/io/qchem/utils.py index 97e8118faba..ecb6b42e690 100644 --- a/pymatgen/io/qchem/utils.py +++ b/pymatgen/io/qchem/utils.py @@ -16,7 +16,7 @@ def read_pattern(text_str, patterns, terminate_on_match=False, postprocess=str): Args: text_str (str): the input string to search for patterns - patterns (dict): A dict of patterns, e.g., + patterns (dict): A dict of patterns, e.g. {"energy": r"energy\\(sigma->0\\)\\s+=\\s+([\\d\\-.]+)"}. terminate_on_match (bool): Whether to terminate when there is at least one match in each key in pattern. diff --git a/pymatgen/io/res.py b/pymatgen/io/res.py index edd4d8938e7..d55400c12fc 100644 --- a/pymatgen/io/res.py +++ b/pymatgen/io/res.py @@ -135,7 +135,7 @@ def __init__(self): self.source: str = "" def _parse_titl(self, line: str) -> AirssTITL | None: - """Parses the TITL entry. Checks for AIRSS values in the entry.""" + """Parse the TITL entry. Checks for AIRSS values in the entry.""" fields = line.split(maxsplit=6) if len(fields) >= 6: # this is probably an AIRSS res file @@ -157,7 +157,7 @@ def _parse_titl(self, line: str) -> AirssTITL | None: return None def _parse_cell(self, line: str) -> ResCELL: - """Parses the CELL entry.""" + """Parse the CELL entry.""" fields = line.split() if len(fields) != 7: raise ResParseError(f"Failed to parse CELL {line=}, expected 7 fields.") @@ -165,7 +165,7 @@ def _parse_cell(self, line: str) -> ResCELL: return ResCELL(field_1, a, b, c, alpha, beta, gamma) def _parse_ion(self, line: str) -> Ion: - """Parses entries in the SFAC block.""" + """Parse entries in the SFAC block.""" fields = line.split() if len(fields) == 6: spin = None @@ -179,7 +179,7 @@ def _parse_ion(self, line: str) -> Ion: return Ion(specie, specie_num, (x, y, z), occ, spin) def _parse_sfac(self, line: str, it: Iterator[str]) -> ResSFAC: - """Parses the SFAC block.""" + """Parse the SFAC block.""" species = list(line.split()) ions = [] try: @@ -193,7 +193,7 @@ def _parse_sfac(self, line: str, it: Iterator[str]) -> ResSFAC: return ResSFAC(species, ions) def _parse_txt(self) -> Res: - """Parses the text of the file.""" + """Parse the text of the file.""" _REMS: list[str] = [] _TITL: AirssTITL | None = None _CELL: ResCELL | None = None @@ -233,14 +233,14 @@ def _parse_txt(self) -> Res: @classmethod def _parse_str(cls, source: str) -> Res: - """Parses the res file as a string.""" + """Parse the res file as a string.""" self = cls() self.source = source return self._parse_txt() @classmethod def _parse_file(cls, filename: str | Path) -> Res: - """Parses the res file as a file.""" + """Parse the res file as a file.""" self = cls() with zopen(filename, mode="r") as file: self.source = file.read() @@ -414,7 +414,7 @@ def from_file(cls, filename: str | Path, parse_rems: Literal["gentle", "strict"] @classmethod def _parse_date(cls, string: str) -> date: - """Parses a date from a string where the date is in the format typically used by CASTEP.""" + """Parse a date from a string where the date is in the format typically used by CASTEP.""" match = cls._date_fmt.search(string) if match is None: raise ResParseError(f"Could not parse the date from {string=}.") @@ -603,8 +603,7 @@ def as_dict(self, verbose: bool = True) -> dict[str, Any]: class ResIO: - """ - Class providing convenience methods for converting a Structure or ComputedStructureEntry + """Convenience methods for converting a Structure or ComputedStructureEntry to/from a string or file in the res format as used by AIRSS. Note: Converting from and back to pymatgen objects is expected to be reversible, i.e. you diff --git a/pymatgen/io/vasp/help.py b/pymatgen/io/vasp/help.py index dea7aad64f4..f057cb09b81 100644 --- a/pymatgen/io/vasp/help.py +++ b/pymatgen/io/vasp/help.py @@ -41,7 +41,7 @@ def get_help(cls, tag: str, fmt: str = "text") -> str: """Get help on a VASP tag. Args: - tag (str): VASP tag, e.g., ISYM. + tag (str): VASP tag, e.g. ISYM. Returns: Help text. diff --git a/pymatgen/io/vasp/inputs.py b/pymatgen/io/vasp/inputs.py index 3987103c442..ded016da0cf 100644 --- a/pymatgen/io/vasp/inputs.py +++ b/pymatgen/io/vasp/inputs.py @@ -680,7 +680,7 @@ def set_temperature(self, temperature: float) -> None: dof = 3 * len(self.structure) - 3 # Remove linear drift (net momentum) - velocities -= np.average(atomic_masses[:, np.newaxis] * velocities, axis=0) / np.average(atomic_masses) + velocities -= np.mean(atomic_masses[:, np.newaxis] * velocities, axis=0) / np.mean(atomic_masses) # Scale velocities due to atomic masses # mean 0 std proportional to sqrt(1/m) @@ -1113,7 +1113,7 @@ def __init__( Kpoints.supported_modes enum types. kpts (2D array): Array of kpoints. Even when only a single specification is required, e.g. in the automatic scheme, - the kpts should still be specified as a 2D array. e.g., + the kpts should still be specified as a 2D array. e.g. [(20,),] or [(2, 2, 2),]. kpts_shift (3x1 array): Shift for kpoints. kpts_weights (list[float]): Optional weights for explicit kpoints. @@ -1293,8 +1293,7 @@ def monkhorst_automatic(cls, kpts: Kpoint = (2, 2, 2), shift: Vector3D = (0, 0, @classmethod def automatic_density(cls, structure: Structure, kppa: float, force_gamma: bool = False) -> Self: - """ - Returns an automatic Kpoint object based on a structure and a kpoint + """Get an automatic Kpoint object based on a structure and a kpoint density. Uses Gamma centered meshes for hexagonal cells and face-centered cells, Monkhorst-Pack grids otherwise. @@ -1341,8 +1340,7 @@ def automatic_density(cls, structure: Structure, kppa: float, force_gamma: bool @classmethod def automatic_gamma_density(cls, structure: Structure, kppa: float) -> Self: - """ - Returns an automatic Kpoint object based on a structure and a kpoint + """Get an automatic Kpoint object based on a structure and a kpoint density. Uses Gamma centered meshes always. For GW. Algorithm: @@ -1381,8 +1379,7 @@ def automatic_gamma_density(cls, structure: Structure, kppa: float) -> Self: @classmethod def automatic_density_by_vol(cls, structure: Structure, kppvol: int, force_gamma: bool = False) -> Self: - """ - Returns an automatic Kpoint object based on a structure and a kpoint + """Get an automatic Kpoint object based on a structure and a kpoint density per inverse Angstrom^3 of reciprocal cell. Algorithm: @@ -1404,8 +1401,7 @@ def automatic_density_by_vol(cls, structure: Structure, kppvol: int, force_gamma def automatic_density_by_lengths( cls, structure: Structure, length_densities: Sequence[float], force_gamma: bool = False ) -> Self: - """ - Returns an automatic Kpoint object based on a structure and a k-point + """Get an automatic Kpoint object based on a structure and a k-point density normalized by lattice constants. Algorithm: @@ -1737,7 +1733,7 @@ class PotcarSingle: Attributes: data (str): POTCAR data as a string. keywords (dict): Keywords parsed from the POTCAR as a dict. All keywords are also - accessible as attributes in themselves. E.g., potcar.enmax, potcar.encut, etc. + accessible as attributes in themselves. e.g. potcar.enmax, potcar.encut, etc. MD5 hashes of the entire POTCAR file and the actual data are validated against a database of known good hashes. Appropriate warnings or errors @@ -1964,7 +1960,7 @@ def element(self) -> str: except ValueError: # VASP incorrectly gives the element symbol for Xe as "X" - # Some potentials, e.g., Zr_sv, gives the symbol as r. + # Some potentials, e.g. Zr_sv, gives the symbol as r. if element == "X": return "Xe" return Element(self.symbol.split("_")[0]).symbol @@ -2012,7 +2008,7 @@ def hash_sha256_from_file(self) -> str | None: @property def sha256_computed_file_hash(self) -> str: - """Computes a SHA256 hash of the PotcarSingle EXCLUDING lines starting with 'SHA256' and 'COPYR'.""" + """Compute a SHA256 hash of the PotcarSingle EXCLUDING lines starting with 'SHA256' and 'COPYR'.""" # We have to remove lines with the hash itself and the copyright # notice to get the correct hash. potcar_list = self.data.split("\n") @@ -2087,7 +2083,7 @@ def is_valid(self) -> bool: Data (actual pseudopotential values in data blocks) For the Data block of POTCAR, there are unformatted data blocks - of unknown length and contents/data type, e.g., you might see + of unknown length and contents/data type, e.g. you might see @@ -2109,7 +2105,7 @@ def is_valid(self) -> bool: possible_potcar_matches = [] # Some POTCARs have an LEXCH (functional used to generate the POTCAR) - # with the expected functional, e.g., the C_d POTCAR for PBE is actually an + # with the expected functional, e.g. the C_d POTCAR for PBE is actually an # LDA pseudopotential. # Thus we have to look for matches in all POTCAR dirs, not just the ones with @@ -2139,7 +2135,7 @@ def parse_fortran_style_str(input_str: str) -> str | bool | float | int: if input_str.upper() == input_str.lower() and input_str[0].isnumeric(): # NB: fortran style floats always include a decimal point. - # While you can set, e.g., x = 1E4, you cannot print/write x without + # While you can set, e.g. x = 1E4, you cannot print/write x without # a decimal point: # `write(6,*) x` --> `10000.0000` in stdout # `write(6,'(E10.0)') x` --> segfault @@ -2267,8 +2263,8 @@ def from_symbol_and_functional( """Make a PotcarSingle from a symbol and functional. Args: - symbol (str): Symbol, e.g., Li_sv - functional (str): Functional, e.g., PBE + symbol (str): Symbol, e.g. Li_sv + functional (str): Functional, e.g. PBE Returns: PotcarSingle @@ -2553,7 +2549,7 @@ def _gen_potcar_summary_stats( titel_key = psp.TITEL.replace(" ", "") # Some POTCARs have the same TITEL, but are named differently - # e.g., there is an "original" PBE POTCAR.Fe_pv and a POTCAR.Fe_pv_new + # e.g. there is an "original" PBE POTCAR.Fe_pv and a POTCAR.Fe_pv_new # which share a TITEL but differ in their contents if titel_key not in new_summary_stats[func]: new_summary_stats[func][titel_key] = [] @@ -2590,7 +2586,7 @@ def __init__( """ Args: symbols (list[str]): Element symbols for POTCAR. This should correspond - to the symbols used by VASP. E.g., "Mg", "Fe_pv", etc. + to the symbols used by VASP. e.g. "Mg", "Fe_pv", etc. functional (str): Functional used. To know what functional options there are, use Potcar.FUNCTIONAL_CHOICES. Note that VASP has different versions of the same functional. By default, the old diff --git a/pymatgen/io/vasp/outputs.py b/pymatgen/io/vasp/outputs.py index 363b82cef8f..295d9c2b461 100644 --- a/pymatgen/io/vasp/outputs.py +++ b/pymatgen/io/vasp/outputs.py @@ -75,7 +75,7 @@ def _parse_v_parameters(val_type, val, filename, param_name): val_type: Value type parsed from vasprun.xml. val: Actual string value parsed for vasprun.xml. filename: Fullpath of vasprun.xml. Used for robust error handling. - E.g., if vasprun.xml contains *** for some Incar parameters, + e.g. if vasprun.xml contains *** for some Incar parameters, the code will try to read from an INCAR file present in the same directory. param_name: Name of parameter. @@ -206,12 +206,12 @@ class Vasprun(MSONable): incar (Incar): Incar object for parameters specified in INCAR file. parameters (Incar): Incar object with parameters that vasp actually used, including all defaults. kpoints (Kpoints): Kpoints object for KPOINTS specified in run. - actual_kpoints (list): List of actual kpoints, e.g., [[0.25, 0.125, 0.08333333], [-0.25, 0.125, 0.08333333], + actual_kpoints (list): List of actual kpoints, e.g. [[0.25, 0.125, 0.08333333], [-0.25, 0.125, 0.08333333], [0.25, 0.375, 0.08333333], ....]. - actual_kpoints_weights (list): List of kpoint weights, E.g., [0.04166667, 0.04166667, 0.04166667, 0.04166667, + actual_kpoints_weights (list): List of kpoint weights, e.g. [0.04166667, 0.04166667, 0.04166667, 0.04166667, 0.04166667, ....]. - atomic_symbols (list): List of atomic symbols, e.g., ["Li", "Fe", "Fe", "P", "P", "P"]. - potcar_symbols (list): List of POTCAR symbols. e.g., ["PAW_PBE Li 17Jan2003", "PAW_PBE Fe 06Sep2000", ..]. + atomic_symbols (list): List of atomic symbols, e.g. ["Li", "Fe", "Fe", "P", "P", "P"]. + potcar_symbols (list): List of POTCAR symbols. e.g. ["PAW_PBE Li 17Jan2003", "PAW_PBE Fe 06Sep2000", ..]. kpoints_opt_props (object): Object whose attributes are the data from KPOINTS_OPT (if present, else None). Attributes of the same name have the same format and meaning as Vasprun (or they are None if absent). Attributes are: tdos, idos, pdos, efermi, eigenvalues, projected_eigenvalues, @@ -538,16 +538,13 @@ def epsilon_ionic(self) -> list[float]: @property def dielectric(self): - """ - Returns: - The real and imaginary part of the dielectric constant (e.g., computed - by RPA) in function of the energy (frequency). Optical properties (e.g. - absorption coefficient) can be obtained through this. - The data is given as a tuple of 3 values containing each of them - the energy, the real part tensor, and the imaginary part tensor - ([energies],[[real_partxx,real_partyy,real_partzz,real_partxy, - real_partyz,real_partxz]],[[imag_partxx,imag_partyy,imag_partzz, - imag_partxy, imag_partyz, imag_partxz]]). + """The real and imaginary part of the dielectric constant (e.g., computed by RPA) in + function of the energy (frequency). Optical properties (e.g. absorption coefficient) + can be obtained through this. The data is given as a tuple of 3 values containing each + of them the energy, the real part tensor, and the imaginary part tensor + ([energies],[[real_partxx,real_partyy,real_partzz,real_partxy, + real_partyz,real_partxz]],[[imag_partxx,imag_partyy,imag_partzz, imag_partxy, + imag_partyz, imag_partxz]]). """ return self.dielectric_data["density"] @@ -660,10 +657,7 @@ def final_energy(self): @property def complete_dos(self): - """ - A complete dos object which incorporates the total dos and all - projected dos. - """ + """A complete DOS object which incorporates the total DOS and all projected DOS.""" final_struct = self.final_structure pdoss = {final_struct[i]: pdos for i, pdos in enumerate(self.pdos)} return CompleteDos(self.final_structure, self.tdos, pdoss) @@ -697,9 +691,8 @@ def hubbards(self) -> dict[str, float]: raise VaspParseError("Length of U value parameters and atomic symbols are mismatched") @property - def run_type(self): - """ - Returns the run type. Currently detects GGA, metaGGA, HF, HSE, B3LYP, + def run_type(self) -> str: + """The run type. Currently detects GGA, metaGGA, HF, HSE, B3LYP, and hybrid functionals based on relevant INCAR tags. LDA is assigned if PAW POTCARs are used and no other functional is detected. @@ -743,41 +736,41 @@ def run_type(self): } if self.parameters.get("AEXX", 1.00) == 1.00: - rt = "HF" + run_type = "HF" elif self.parameters.get("HFSCREEN", 0.30) == 0.30: - rt = "HSE03" + run_type = "HSE03" elif self.parameters.get("HFSCREEN", 0.20) == 0.20: - rt = "HSE06" + run_type = "HSE06" elif self.parameters.get("AEXX", 0.20) == 0.20: - rt = "B3LYP" + run_type = "B3LYP" elif self.parameters.get("LHFCALC", True): - rt = "PBEO or other Hybrid Functional" + run_type = "PBEO or other Hybrid Functional" elif self.incar.get("METAGGA") and self.incar.get("METAGGA") not in [ "--", "None", ]: incar_tag = self.incar.get("METAGGA", "").strip().upper() - rt = METAGGA_TYPES.get(incar_tag, incar_tag) + run_type = METAGGA_TYPES.get(incar_tag, incar_tag) elif self.parameters.get("GGA"): incar_tag = self.parameters.get("GGA", "").strip().upper() - rt = GGA_TYPES.get(incar_tag, incar_tag) + run_type = GGA_TYPES.get(incar_tag, incar_tag) elif self.potcar_symbols[0].split()[0] == "PAW": - rt = "LDA" + run_type = "LDA" else: - rt = "unknown" + run_type = "unknown" warnings.warn("Unknown run type!") if self.is_hubbard or self.parameters.get("LDAU", True): - rt += "+U" + run_type += "+U" if self.parameters.get("LUSE_VDW", False): - rt += "+rVV10" + run_type += "+rVV10" elif self.incar.get("IVDW") in IVDW_TYPES: - rt += "+vdW-" + IVDW_TYPES[self.incar.get("IVDW")] + run_type += "+vdW-" + IVDW_TYPES[self.incar.get("IVDW")] elif self.incar.get("IVDW"): - rt += "+vdW-unknown" + run_type += "+vdW-unknown" - return rt + return run_type @property def is_hubbard(self) -> bool: @@ -800,8 +793,7 @@ def md_n_steps(self) -> int: return self.nionic_steps def get_computed_entry(self, inc_structure=True, parameters=None, data=None, entry_id: str | None = None): - """ - Returns a ComputedEntry or ComputedStructureEntry from the Vasprun. + """Get a ComputedEntry or ComputedStructureEntry from the Vasprun. Args: inc_structure (bool): Set to True if you want @@ -1008,12 +1000,10 @@ def get_band_structure( @property def eigenvalue_band_properties(self): - """ - Band properties from the eigenvalues as a tuple, - (band gap, cbm, vbm, is_band_gap_direct). In the case of separate_spins=True, - the band gap, cbm, vbm, and is_band_gap_direct are each lists of length 2, - with index 0 representing the spin-up channel and index 1 representing - the spin-down channel. + """Band properties from the eigenvalues as a tuple, (band gap, cbm, vbm, is_band_gap_direct). + In the case of separate_spins=True, the band gap, cbm, vbm, and is_band_gap_direct are each + lists of length 2, with index 0 representing the spin-up channel and index 1 representing the + spin-down channel. """ vbm = -float("inf") vbm_kpoint = None @@ -1112,7 +1102,7 @@ def get_potcars(self, path: str | Path | bool) -> Potcar | None: potcar_paths = [str(path)] else: # the abspath is needed here in cases where no leading directory is specified, - # e.g., Vasprun("vasprun.xml"). see gh-3586: + # e.g. Vasprun("vasprun.xml"). see gh-3586: search_path = os.path.dirname(os.path.abspath(self.filename)) if path is True else str(path) potcar_paths = [ @@ -1781,18 +1771,18 @@ class Outcar: are always present. Attributes: - magnetization (tuple): Magnetization on each ion as a tuple of dict, e.g., + magnetization (tuple): Magnetization on each ion as a tuple of dict, e.g. ({"d": 0.0, "p": 0.003, "s": 0.002, "tot": 0.005}, ... ) chemical_shielding (dict): Chemical shielding on each ion as a dictionary with core and valence contributions. unsym_cs_tensor (list): Unsymmetrized chemical shielding tensor matrixes on each ion as a list. - e.g., [[[sigma11, sigma12, sigma13], [sigma21, sigma22, sigma23], [sigma31, sigma32, sigma33]], ...] + e.g. [[[sigma11, sigma12, sigma13], [sigma21, sigma22, sigma23], [sigma31, sigma32, sigma33]], ...] cs_g0_contribution (np.array): G=0 contribution to chemical shielding. 2D rank 3 matrix. - cs_core_contribution (dict): Core contribution to chemical shielding. dict. e.g., + cs_core_contribution (dict): Core contribution to chemical shielding. dict. e.g. {'Mg': -412.8, 'C': -200.5, 'O': -271.1} - efg (tuple): Electric Field Gradient (EFG) tensor on each ion as a tuple of dict, e.g., + efg (tuple): Electric Field Gradient (EFG) tensor on each ion as a tuple of dict, e.g. ({"cq": 0.1, "eta", 0.2, "nuclear_quadrupole_moment": 0.3}, {"cq": 0.7, "eta", 0.8, "nuclear_quadrupole_moment": 0.9}, ...) - charge (tuple): Charge on each ion as a tuple of dict, e.g., + charge (tuple): Charge on each ion as a tuple of dict, e.g. ({"p": 0.154, "s": 0.078, "d": 0.0, "tot": 0.232}, ...) is_stopped (bool): True if OUTCAR is from a stopped run (using STOPCAR, see VASP Manual). run_stats (dict): Various useful run stats as a dict including "System time (sec)", "Total CPU time used (sec)", @@ -2129,7 +2119,7 @@ def read_pattern(self, patterns, reverse=False, terminate_on_match=False, postpr arguments. Args: - patterns (dict): A dict of patterns, e.g., + patterns (dict): A dict of patterns, e.g. {"energy": r"energy\\(sigma->0\\)\\s+=\\s+([\\d\\-.]+)"}. reverse (bool): Read files in reverse. Defaults to false. Useful for large files, esp OUTCARs, especially when used with @@ -2235,7 +2225,7 @@ def read_table_pattern( return retained_data def read_electrostatic_potential(self): - """Parses the eletrostatic potential for the last ionic step.""" + """Parse the eletrostatic potential for the last ionic step.""" pattern = {"ngf": r"\s+dimension x,y,z NGXF=\s+([\.\-\d]+)\sNGYF=\s+([\.\-\d]+)\sNGZF=\s+([\.\-\d]+)"} self.read_pattern(pattern, postprocess=int) self.ngf = self.data.get("ngf", [[]])[0] @@ -3869,18 +3859,17 @@ def get_projection_on_elements(self, structure: Structure): return dico def get_occupation(self, atom_index, orbital): - """ - Returns the occupation for a particular orbital of a particular atom. + """Get the occupation for a particular orbital of a particular atom. Args: atom_num (int): Index of atom in the PROCAR. It should be noted that VASP uses 1-based indexing for atoms, but this is converted to 0-based indexing in this parser to be consistent with representation of structures in pymatgen. - orbital (str): An orbital. If it is a single character, e.g., s, + orbital (str): An orbital. If it is a single character, e.g. s, p, d or f, the sum of all s-type, p-type, d-type or f-type orbitals occupations are returned respectively. If it is a - specific orbital, e.g., px, dxy, etc., only the occupation + specific orbital, e.g. px, dxy, etc., only the occupation of that orbital is returned. Returns: @@ -3900,13 +3889,13 @@ class Oszicar: information about a run. Attributes: - electronic_steps (list): All electronic steps as a list of list of dict. e.g., + electronic_steps (list): All electronic steps as a list of list of dict. e.g. [[{"rms": 160.0, "E": 4507.24605593, "dE": 4507.2, "N": 1, "deps": -17777.0, "ncg": 16576}, ...], [....] where electronic_steps[index] refers the list of electronic steps in one ionic_step, electronic_steps[index][subindex] refers to a particular electronic step at subindex in ionic step at index. The dict of properties depends on the type of VASP run, but in general, "E", "dE" and "rms" should be present in almost all runs. - ionic_steps (list): All ionic_steps as a list of dict, e.g., + ionic_steps (list): All ionic_steps as a list of dict, e.g. [{"dE": -526.36, "E0": -526.36024, "mag": 0.0, "F": -526.36024}, ...] This is the typical output from VASP at the end of each ionic step. The stored dict might be different depending on the type of VASP run. @@ -3952,9 +3941,8 @@ def smart_convert(header, num): @property def all_energies(self): - """ - Compilation of all energies from all electronic steps and ionic steps - as a tuple of list of energies, e.g., + """Compilation of all energies from all electronic steps and ionic steps + as a tuple of list of energies, e.g. ((4507.24605593, 143.824705755, -512.073149912, ...), ...). """ all_energies = [] @@ -4032,8 +4020,7 @@ def get_band_structure_from_vasp_multiple_branches(dir_name, efermi=None, projec class Xdatcar: - """ - Class representing an XDATCAR file. Only tested with VASP 5.x files. + """XDATCAR output file. Only tested with VASP 5.x files. Attributes: structures (list): List of structures parsed from XDATCAR. @@ -4762,8 +4749,7 @@ def get_parchg( phase: bool = False, scale: int = 2, ) -> Chgcar: - """ - Generates a Chgcar object, which is the charge density of the specified + """Generate a Chgcar object, which is the charge density of the specified wavefunction. This function generates a Chgcar object with the charge density of the @@ -4950,9 +4936,8 @@ def __init__(self, filename, occu_tol=1e-8, separate_spins=False) -> None: self.eigenvalues[Spin.down][ikpt, i, 1] = sl[4] @property - def eigenvalue_band_properties(self): - """ - Band properties from the eigenvalues as a tuple, + def eigenvalue_band_properties(self) -> tuple: + """Band properties from the eigenvalues as a tuple, (band gap, cbm, vbm, is_band_gap_direct). In the case of separate_spins=True, the band gap, cbm, vbm, and is_band_gap_direct are each lists of length 2, with index 0 representing the spin-up channel and index 1 representing diff --git a/pymatgen/io/vasp/sets.py b/pymatgen/io/vasp/sets.py index 7569d10cceb..caae8833a41 100644 --- a/pymatgen/io/vasp/sets.py +++ b/pymatgen/io/vasp/sets.py @@ -7,7 +7,7 @@ Read the following carefully before implementing new input sets: 1. 99% of what needs to be done can be done by specifying user_incar_settings to override some of the defaults of - various input sets. Unless there is an extremely good reason to add a new set, **do not** add one. E.g., if you want + various input sets. Unless there is an extremely good reason to add a new set, **do not** add one. e.g. if you want to turn the Hubbard U off, just set "LDAU": False as a user_incar_setting. 2. All derivative input sets should inherit appropriate configurations (e.g., from MPRelaxSet), and more often than not, DictSet should be the superclass. Proper superclass delegation should be used where possible. In particular, @@ -22,7 +22,7 @@ 2. user_incar_settings, user_kpoints_settings and user__settings are ABSOLUTE. Any new sets you implement must obey this. If a user wants to override your settings, you assume he knows what he is doing. Do not magically override user supplied settings. You can issue a warning if you think the user is wrong. -3. All input sets must save all supplied args and kwargs as instance variables. E.g., self.arg = arg and +3. All input sets must save all supplied args and kwargs as instance variables. e.g. self.arg = arg and self.kwargs = kwargs in the __init__. This ensures the as_dict and from_dict work correctly. """ @@ -271,7 +271,7 @@ class DictSet(VaspInputSet): 2. If the species of the site has a spin setting, that is used. This can be set with structure.add_spin_by_element(). 3. If the species itself has a particular setting in the config file, that - is used, e.g., Mn3+ may have a different magmom than Mn4+. + is used, e.g. Mn3+ may have a different magmom than Mn4+. 4. Lastly, the element symbol itself is checked in the config file. If there are no settings, a default value of 0.6 is used. @@ -283,7 +283,7 @@ class DictSet(VaspInputSet): files_to_transfer (dict): A dictionary of {filename: filepath}. This allows the transfer of files from a previous calculation. user_incar_settings (dict): User INCAR settings. This allows a user to override - INCAR settings, e.g., setting a different MAGMOM for various elements or + INCAR settings, e.g. setting a different MAGMOM for various elements or species. Note that in the new scheme, ediff_per_atom and hubbard_u are no longer args. Instead, the CONFIG supports EDIFF_PER_ATOM and EDIFF keys. The former scales with # of atoms, the latter does not. If both are present, @@ -298,9 +298,9 @@ class DictSet(VaspInputSet): incar settings. Finally, KSPACING is a special setting and can be set to "auto" in which the KSPACING is set automatically based on the band gap. user_kpoints_settings (dict or Kpoints): Allow user to override kpoints setting - by supplying a dict. E.g., {"reciprocal_density": 1000}. User can also + by supplying a dict. e.g. {"reciprocal_density": 1000}. User can also supply Kpoints object. - user_potcar_settings (dict): Allow user to override POTCARs. E.g., {"Gd": + user_potcar_settings (dict): Allow user to override POTCARs. e.g. {"Gd": "Gd_3"}. This is generally not recommended. constrain_total_magmom (bool): Whether to constrain the total magmom (NUPDOWN in INCAR) to be the sum of the expected MAGMOM for all species. @@ -1029,8 +1029,7 @@ def override_from_prev_calc(self, prev_calc_dir="."): @classmethod def from_prev_calc(cls, prev_calc_dir: str, **kwargs) -> Self: - """ - Generate a set of VASP input files for static calculations from a + """Generate a set of VASP input files for static calculations from a directory of previous VASP run. Args: @@ -2079,8 +2078,7 @@ def incar_updates(self) -> dict: @classmethod def from_prev_calc(cls, prev_calc_dir: str, mode: str = "DIAG", **kwargs) -> Self: - """ - Generate a set of VASP input files for GW or BSE calculations from a + """Generate a set of VASP input files for GW or BSE calculations from a directory of previous Exact Diag VASP run. Args: @@ -2134,10 +2132,10 @@ def incar_updates(self) -> dict: @property def kpoints_updates(self): - """Get updates to the kpoints configuration for this calculation type. + """Updates to the kpoints configuration for this calculation type. k_product, default to 50, is kpoint number * length for a & b - directions, also for c direction in bulk calculations + directions, also for c direction in bulk calculations Automatic mesh & Gamma is the default setting. """ # To get input sets, the input structure has to has the same number @@ -2161,7 +2159,7 @@ def kpoints_updates(self): def as_dict(self, verbosity=2): """ Args: - verbosity (int): Verbosity of dict. E.g., whether to include Structure. + verbosity (int): Verbosity of dict. e.g. whether to include Structure. Returns: MSONable dict @@ -2198,10 +2196,8 @@ class MVLGBSet(DictSet): @property def kpoints_updates(self): - """ - k_product, default to 40, is kpoint number * length for a & b - directions, also for c direction in bulk calculations - Automatic mesh & Gamma is the default setting. + """k_product is kpoint number * length for a & b directions, also for c direction + in bulk calculations Automatic mesh & Gamma is the default setting. """ # use k_product to calculate kpoints, k_product = kpts[0][0] * a lengths = self.structure.lattice.abc @@ -2394,7 +2390,7 @@ class MITMDSet(DictSet): @property def incar_updates(self): - """Get updates to the INCAR config for this calculation type.""" + """Updates to the INCAR config for this calculation type.""" # MD default settings return { "TEBEG": self.start_temp, diff --git a/pymatgen/io/xcrysden.py b/pymatgen/io/xcrysden.py index 362fdb87d72..85f6548d784 100644 --- a/pymatgen/io/xcrysden.py +++ b/pymatgen/io/xcrysden.py @@ -26,8 +26,7 @@ def __init__(self, structure: Structure): self.structure = structure def to_str(self, atom_symbol: bool = True) -> str: - """ - Returns a string with the structure in XSF format + """Get a string with the structure in XSF format See http://www.xcrysden.org/doc/XSF.html. Args: diff --git a/pymatgen/io/xyz.py b/pymatgen/io/xyz.py index bbd56c51261..79aa6a296fe 100644 --- a/pymatgen/io/xyz.py +++ b/pymatgen/io/xyz.py @@ -42,8 +42,7 @@ def __init__(self, mol: Molecule | Structure | Sequence[Molecule | Structure], c @property def molecule(self) -> Molecule: - """ - Returns molecule associated with this XYZ. In case of multi-frame + """Get molecule associated with this XYZ. In case of multi-frame XYZ, returns the last frame. """ return self._mols[-1] # type: ignore[return-value] @@ -112,8 +111,7 @@ def from_file(cls, filename: str | Path) -> Self: return cls.from_str(file.read()) def as_dataframe(self): - """ - Generates a coordinates data frame with columns: atom, x, y, and z + """Generate a coordinates data frame with columns: atom, x, y, and z In case of multiple frame XYZ, returns the last frame. Returns: diff --git a/pymatgen/io/zeopp.py b/pymatgen/io/zeopp.py index 36f2d78b8e2..cd054357fcd 100644 --- a/pymatgen/io/zeopp.py +++ b/pymatgen/io/zeopp.py @@ -152,8 +152,7 @@ def from_file(cls, filename: str | Path) -> Self: class ZeoVoronoiXYZ(XYZ): - """ - Class to read Voronoi Nodes from XYZ file written by Zeo++. + """Read Voronoi Nodes from XYZ file written by Zeo++. The sites have an additional column representing the voronoi node radius. The voronoi node radius is represented by the site property voronoi_radius. """ diff --git a/pymatgen/phonon/thermal_displacements.py b/pymatgen/phonon/thermal_displacements.py index 314e8965344..67121a7641d 100644 --- a/pymatgen/phonon/thermal_displacements.py +++ b/pymatgen/phonon/thermal_displacements.py @@ -461,7 +461,7 @@ def from_Ucif( def to_structure_with_site_properties_Ucif(self) -> Structure: """Transfers this object into a structure with site properties (Ucif). This is useful for sorting the atoms in the structure including site properties. - E.g., with code like this: + e.g. with code like this: def sort_order(site): return [site.specie.X, site.frac_coords[0], site.frac_coords[1], site.frac_coords[2]] new_structure0 = Structure.from_sites(sorted(structure0, key=sort_order)). diff --git a/pymatgen/symmetry/analyzer.py b/pymatgen/symmetry/analyzer.py index 2d2eea10e3d..b85651260e9 100644 --- a/pymatgen/symmetry/analyzer.py +++ b/pymatgen/symmetry/analyzer.py @@ -170,7 +170,7 @@ def get_point_group_symbol(self) -> str: return spglib.get_pointgroup(rotations)[0].strip() def get_crystal_system(self) -> CrystalSystem: - """Get the crystal system for the structure, e.g., (triclinic, orthorhombic, + """Get the crystal system for the structure, e.g. (triclinic, orthorhombic, cubic, etc.). Raises: @@ -200,7 +200,7 @@ def get_crystal_system(self) -> CrystalSystem: return "cubic" def get_lattice_type(self) -> LatticeType: - """Get the lattice for the structure, e.g., (triclinic, orthorhombic, cubic, + """Get the lattice for the structure, e.g. (triclinic, orthorhombic, cubic, etc.).This is the same as the crystal system with the exception of the hexagonal/rhombohedral lattice. @@ -1628,7 +1628,7 @@ def __str__(self): class PointGroupOperations(list): - """Defines a point group, which is essentially a sequence of symmetry operations. + """Represents a point group, which is a sequence of symmetry operations. Attributes: sch_symbol (str): Schoenflies symbol of the point group. diff --git a/pymatgen/symmetry/bandstructure.py b/pymatgen/symmetry/bandstructure.py index d714b6edd2f..05d416a0fbe 100644 --- a/pymatgen/symmetry/bandstructure.py +++ b/pymatgen/symmetry/bandstructure.py @@ -140,38 +140,29 @@ def __init__( @property def path_type(self): - """ - Returns: - The type of kpath chosen. - """ + """The type of kpath chosen.""" return self._path_type @property def label_index(self): - """ - Returns: - The correspondence between numbers and kpoint symbols for the + """The correspondence between numbers and kpoint symbols for the combined kpath generated when path_type = 'all'. None otherwise. """ return self._label_index @property def equiv_labels(self): - """ - Returns: - The correspondence between the kpoint symbols in the Latimer and - Munro convention, Setyawan and Curtarolo, and Hinuma - conventions respectively. Only generated when path_type = 'all'. + """The correspondence between the kpoint symbols in the Latimer and + Munro convention, Setyawan and Curtarolo, and Hinuma + conventions respectively. Only generated when path_type = 'all'. """ return self._equiv_labels @property def path_lengths(self): - """ - Returns: - List of lengths of the Latimer and Munro, Setyawan and Curtarolo, and Hinuma - conventions in the combined HighSymmKpath object when path_type = 'all' respectively. - None otherwise. + """List of lengths of the Latimer and Munro, Setyawan and Curtarolo, and Hinuma + conventions in the combined HighSymmKpath object when path_type = 'all' respectively. + None otherwise. """ return self._path_lengths diff --git a/pymatgen/symmetry/groups.py b/pymatgen/symmetry/groups.py index b83e5c28a32..d97af296c7a 100644 --- a/pymatgen/symmetry/groups.py +++ b/pymatgen/symmetry/groups.py @@ -201,10 +201,10 @@ def __init__(self, int_symbol: str) -> None: represented by an underscore. For example, "P6_3/mmc". Alternative settings can be accessed by adding a ":identifier". For example, the hexagonal setting for rhombohedral cells can be - accessed by adding a ":H", e.g., "R-3m:H". To find out all + accessed by adding a ":H", e.g. "R-3m:H". To find out all possible settings for a spacegroup, use the get_settings() classmethod. Alternative origin choices can be indicated by a - translation vector, e.g., 'Fm-3m(a-1/4,b-1/4,c-1/4)'. + translation vector, e.g. 'Fm-3m(a-1/4,b-1/4,c-1/4)'. """ from pymatgen.core.operations import SymmOp @@ -419,7 +419,7 @@ def check(param, ref, tolerance): def crystal_system(self) -> CrystalSystem: """ Returns: - str: Crystal system of the space group, e.g., cubic, hexagonal, etc. + str: Crystal system of the space group, e.g. cubic, hexagonal, etc. """ num = self.int_number if num <= 2: @@ -549,7 +549,7 @@ def sg_symbol_from_int_number(int_number: int, hexagonal: bool = True) -> str: def in_array_list(array_list: list[np.ndarray] | np.ndarray, arr: np.ndarray, tol: float = 1e-5) -> bool: """Extremely efficient nd-array comparison using numpy's broadcasting. This function checks if a particular array a, is present in a list of arrays. - It works for arrays of any size, e.g., even matrix searches. + It works for arrays of any size, e.g. even matrix searches. Args: array_list ([array]): A list of arrays to compare to. diff --git a/pymatgen/symmetry/kpath.py b/pymatgen/symmetry/kpath.py index 462754fd057..9ff00c2f28e 100644 --- a/pymatgen/symmetry/kpath.py +++ b/pymatgen/symmetry/kpath.py @@ -63,42 +63,26 @@ def __init__(self, structure: Structure, symprec: float = 0.01, angle_tolerance= @property def structure(self): - """ - Returns: - The input structure. - """ + """The input structure.""" return self._structure @property def lattice(self): - """ - Returns: - The real space lattice. - """ + """The real space lattice.""" return self._latt @property def rec_lattice(self): - """ - Returns: - The reciprocal space lattice. - """ + """The reciprocal space lattice.""" return self._rec_lattice @property def kpath(self): - """ - Returns: - The symmetry line path in reciprocal space. - """ + """The symmetry line path in reciprocal space.""" return self._kpath def get_kpoints(self, line_density=20, coords_are_cartesian=True): - """ - Returns: - kpoints along the path in Cartesian coordinates - together with the critical-point labels. - """ + """Get kpoints along the path in Cartesian coordinates together with the critical-point labels.""" list_k_points = [] sym_point_labels = [] for b in self.kpath["path"]: @@ -278,26 +262,17 @@ def __init__(self, structure: Structure, symprec: float = 0.01, angle_tolerance= @property def conventional(self): - """ - Returns: - The conventional cell structure. - """ + """The conventional cell structure.""" return self._conv @property def prim(self): - """ - Returns: - The primitive cell structure. - """ + """The primitive cell structure.""" return self._prim @property def prim_rec(self): - """ - Returns: - The primitive reciprocal cell structure. - """ + """The primitive reciprocal cell structure.""" return self._rec_lattice def cubic(self): @@ -1089,11 +1064,9 @@ def __init__( @property def mag_type(self): - """ - Returns: - The type of magnetic space group as a string. Current implementation does not - distinguish between types 3 and 4, so return value is '3/4'. If has_magmoms is - False, returns '0'. + """The type of magnetic space group as a string. Current implementation does not + distinguish between types 3 and 4, so return value is '3/4'. If has_magmoms is + False, returns '0'. """ return self._mag_type diff --git a/pymatgen/symmetry/maggroups.py b/pymatgen/symmetry/maggroups.py index 6fd39f752f8..b811996cece 100644 --- a/pymatgen/symmetry/maggroups.py +++ b/pymatgen/symmetry/maggroups.py @@ -150,7 +150,7 @@ def _get_point_operator(idx): } def _parse_operators(b): - """Parses compact binary representation into list of MagSymmOps.""" + """Parse compact binary representation into list of MagSymmOps.""" if len(b) == 0: # e.g. if magtype != 4, OG setting == BNS setting, and b == [] for OG symmops return None raw_symops = [b[i : i + 6] for i in range(0, len(b), 6)] @@ -178,7 +178,7 @@ def _parse_operators(b): return symops def _parse_wyckoff(b): - """Parses compact binary representation into list of Wyckoff sites.""" + """Parse compact binary representation into list of Wyckoff sites.""" if len(b) == 0: return None @@ -232,7 +232,7 @@ def get_label(idx): return wyckoff_sites def _parse_lattice(b): - """Parses compact binary representation into list of lattice vectors/centerings.""" + """Parse compact binary representation into list of lattice vectors/centerings.""" if len(b) == 0: return None raw_lattice = [b[i : i + 4] for i in range(0, len(b), 4)] @@ -252,7 +252,7 @@ def _parse_lattice(b): return lattice def _parse_transformation(b): - """Parses compact binary representation into transformation between OG and BNS settings.""" + """Parse compact binary representation into transformation between OG and BNS settings.""" if len(b) == 0: return None # capital letters used here by convention, @@ -313,7 +313,7 @@ def __eq__(self, other: object) -> bool: @property def crystal_system(self): - """Crystal system, e.g., cubic, hexagonal, etc.""" + """Crystal system, e.g. cubic, hexagonal, etc.""" i = self._data["bns_number"][0] if i <= 2: return "triclinic" diff --git a/pymatgen/transformations/advanced_transformations.py b/pymatgen/transformations/advanced_transformations.py index e0228839ca6..720c0f166ba 100644 --- a/pymatgen/transformations/advanced_transformations.py +++ b/pymatgen/transformations/advanced_transformations.py @@ -982,14 +982,14 @@ def __init__( ): """ Args: - dopant (Species-like): E.g., Al3+. Must have oxidation state. - ionic_radius_tol (float): E.g., Fractional allowable ionic radii + dopant (Species-like): e.g. Al3+. Must have oxidation state. + ionic_radius_tol (float): e.g. Fractional allowable ionic radii mismatch for dopant to fit into a site. Default of inf means that any dopant with the right oxidation state is allowed. min_length (float): Min. lattice parameter between periodic images of dopant. Defaults to 10A for now. alio_tol (int): If this is not 0, attempt will be made to dope - sites with oxidation_states +- alio_tol of the dopant. E.g., + sites with oxidation_states +- alio_tol of the dopant. e.g. 1 means that the ions like Ca2+ and Ti4+ are considered as potential doping sites for Al3+. codopant (bool): If True, doping will be carried out with a @@ -1912,9 +1912,9 @@ def __init__( """ Args: scaling (int or list): Scaling factor to determine supercell. Two options are possible: - a. (preferred) Scales number of atoms, e.g., for a structure with 8 atoms, + a. (preferred) Scales number of atoms, e.g. for a structure with 8 atoms, scaling=4 would lead to a 32 atom supercell - b. A sequence of three scaling factors, e.g., [2, 1, 1], which + b. A sequence of three scaling factors, e.g. [2, 1, 1], which specifies that the supercell should have dimensions 2a x b x c cluster_size_and_shell (Optional[Dict[int, int]]): Dictionary of cluster interactions with entries in the form number of atoms: nearest neighbor shell diff --git a/pymatgen/transformations/site_transformations.py b/pymatgen/transformations/site_transformations.py index 815db246d6c..da0199ae21e 100644 --- a/pymatgen/transformations/site_transformations.py +++ b/pymatgen/transformations/site_transformations.py @@ -31,8 +31,8 @@ class InsertSitesTransformation(AbstractTransformation): def __init__(self, species, coords, coords_are_cartesian=False, validate_proximity=True): """ Args: - species: A list of species. e.g., ["Li", "Fe"] - coords: A list of coords corresponding to those species. e.g., + species: A list of species. e.g. ["Li", "Fe"] + coords: A list of coords corresponding to those species. e.g. [[0,0,0],[0.5,0.5,0.5]]. coords_are_cartesian (bool): Set to True if coords are given in Cartesian coords. Defaults to False. @@ -88,7 +88,7 @@ def __init__(self, indices_species_map): """ Args: indices_species_map: A dict containing the species mapping in - int-string pairs. E.g., { 1:"Na"} or {2:"Mn2+"}. Multiple + int-string pairs. e.g. { 1:"Na"} or {2:"Mn2+"}. Multiple substitutions can be done. Overloaded to accept sp_and_occu dictionary. E.g. {1: {"Ge":0.75, "C":0.25} }, which substitutes a single species with multiple species to generate a @@ -133,7 +133,7 @@ class RemoveSitesTransformation(AbstractTransformation): def __init__(self, indices_to_remove): """ Args: - indices_to_remove: List of indices to remove. E.g., [0, 1, 2]. + indices_to_remove: List of indices to remove. e.g. [0, 1, 2]. """ self.indices_to_remove = indices_to_remove @@ -210,11 +210,8 @@ def __repr__(self): ) @property - def inverse(self): - """ - Returns: - TranslateSitesTransformation with the reverse translation. - """ + def inverse(self) -> TranslateSitesTransformation: + """TranslateSitesTransformation with the reverse translation.""" return TranslateSitesTransformation(self.indices_to_move, -self.translation_vector, self.vector_in_frac_coords) @property @@ -279,7 +276,7 @@ def __init__(self, indices, fractions, algo=ALGO_COMPLETE): A list of list of indices, e.g. [[0, 1], [2, 3, 4, 5]]. fractions: The corresponding fractions to remove. Must be same length as - indices. e.g., [0.5, 0.25] + indices. e.g. [0.5, 0.25] algo: This parameter allows you to choose the algorithm to perform ordering. Use one of PartialRemoveSpecieTransformation.ALGO_* diff --git a/pymatgen/transformations/standard_transformations.py b/pymatgen/transformations/standard_transformations.py index 40f56c4beb1..37282fd9ffb 100644 --- a/pymatgen/transformations/standard_transformations.py +++ b/pymatgen/transformations/standard_transformations.py @@ -39,7 +39,7 @@ class RotationTransformation(AbstractTransformation): def __init__(self, axis, angle, angle_in_radians=False): """ Args: - axis (3x1 array): Axis of rotation, e.g., [1, 0, 0] + axis (3x1 array): Axis of rotation, e.g. [1, 0, 0] angle (float): Angle to rotate angle_in_radians (bool): Set to True if angle is supplied in radians. Else degrees are assumed. @@ -86,7 +86,7 @@ def __init__(self, oxidation_states): """ Args: oxidation_states (dict): Oxidation states supplied as a dict, - e.g., {"Li":1, "O":-2}. + e.g. {"Li":1, "O":-2}. """ self.oxidation_states = oxidation_states @@ -203,7 +203,7 @@ def __init__(self, scaling_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1))): """ Args: scaling_matrix: A matrix of transforming the lattice vectors. - Defaults to the identity matrix. Has to be all integers. e.g., + Defaults to the identity matrix. Has to be all integers. e.g. [[2,1,0],[0,3,0],[0,0,1]] generates a new structure with lattice vectors a" = 2a + b, b" = 3b, c" = c where a, b, and c are the lattice vectors of the original structure. @@ -311,7 +311,7 @@ def __init__( """ Args: species_map: A dict or list of tuples containing the species mapping in - string-string pairs. E.g., {"Li": "Na"} or [("Fe2+","Mn2+")]. + string-string pairs. e.g. {"Li": "Na"} or [("Fe2+","Mn2+")]. Multiple substitutions can be done. Overloaded to accept sp_and_occu dictionary E.g. {"Si: {"Ge":0.75, "C":0.25}}, which substitutes a single species with multiple species to @@ -361,7 +361,7 @@ class RemoveSpeciesTransformation(AbstractTransformation): def __init__(self, species_to_remove): """ Args: - species_to_remove: List of species to remove. E.g., ["Li", "Mn"]. + species_to_remove: List of species to remove. e.g. ["Li", "Mn"]. """ self.species_to_remove = species_to_remove @@ -413,9 +413,9 @@ class PartialRemoveSpecieTransformation(AbstractTransformation): def __init__(self, specie_to_remove, fraction_to_remove, algo=ALGO_FAST): """ Args: - specie_to_remove: Species to remove. Must have oxidation state E.g., + specie_to_remove: Species to remove. Must have oxidation state e.g. "Li+" - fraction_to_remove: Fraction of specie to remove. E.g., 0.5 + fraction_to_remove: Fraction of specie to remove. e.g. 0.5 algo: This parameter allows you to choose the algorithm to perform ordering. Use one of PartialRemoveSpecieTransformation.ALGO_* variables to set the algo. @@ -945,7 +945,7 @@ def __init__(self, unrelaxed_structure, relaxed_structure, species_map=None): species_map (dict): A dict or list of tuples containing the species mapping in string-string pairs. The first species corresponds to the relaxed structure while the second corresponds to the species in the - structure to be scaled. E.g., {"Li":"Na"} or [("Fe2+","Mn2+")]. + structure to be scaled. e.g. {"Li":"Na"} or [("Fe2+","Mn2+")]. Multiple substitutions can be done. Overloaded to accept sp_and_occu dictionary E.g. {"Si: {"Ge":0.75, "C":0.25}}, which substitutes a single species with multiple species to diff --git a/pymatgen/transformations/transformation_abc.py b/pymatgen/transformations/transformation_abc.py index 8465ce0caba..f5c62800b2b 100644 --- a/pymatgen/transformations/transformation_abc.py +++ b/pymatgen/transformations/transformation_abc.py @@ -1,4 +1,4 @@ -"""Defines an abstract base class contract for Transformation object.""" +"""Abstract base class for structure transformations.""" from __future__ import annotations diff --git a/pymatgen/util/coord.py b/pymatgen/util/coord.py index 274684fb69d..dc814112659 100644 --- a/pymatgen/util/coord.py +++ b/pymatgen/util/coord.py @@ -37,7 +37,7 @@ def find_in_coord_list(coord_list, coord, atol: float = 1e-8): array. Returns: - Indices of matches, e.g., [0, 1, 2, 3]. Empty list if not found. + Indices of matches, e.g. [0, 1, 2, 3]. Empty list if not found. """ if len(coord_list) == 0: return [] @@ -46,7 +46,7 @@ def find_in_coord_list(coord_list, coord, atol: float = 1e-8): def in_coord_list(coord_list, coord, atol: float = 1e-8) -> bool: - """Tests if a particular coord is within a coord_list. + """Test if a particular coord is within a coord_list. Args: coord_list: List of coords to test @@ -61,7 +61,7 @@ def in_coord_list(coord_list, coord, atol: float = 1e-8) -> bool: def is_coord_subset(subset: ArrayLike, superset: ArrayLike, atol: float = 1e-8) -> bool: - """Tests if all coords in subset are contained in superset. + """Test if all coords in subset are contained in superset. Doesn't use periodic boundary conditions. Args: @@ -169,7 +169,7 @@ def pbc_diff(frac_coords1: ArrayLike, frac_coords2: ArrayLike, pbc: PbcLike = (T account periodic boundary conditions. Args: - frac_coords1: First set of fractional coordinates. e.g., [0.5, 0.6, + frac_coords1: First set of fractional coordinates. e.g. [0.5, 0.6, 0.7] or [[1.1, 1.2, 4.3], [0.5, 0.6, 0.7]]. It can be a single coord or any array of coords. frac_coords2: Second set of fractional coordinates. @@ -192,7 +192,7 @@ def pbc_shortest_vectors(lattice, frac_coords1, frac_coords2, mask=None, return_ Args: lattice: lattice to use - frac_coords1: First set of fractional coordinates. e.g., [0.5, 0.6, 0.7] + frac_coords1: First set of fractional coordinates. e.g. [0.5, 0.6, 0.7] or [[1.1, 1.2, 4.3], [0.5, 0.6, 0.7]]. It can be a single coord or any array of coords. frac_coords2: Second set of fractional coordinates. @@ -223,7 +223,7 @@ def find_in_coord_list_pbc( axis of the lattice. Returns: - Indices of matches, e.g., [0, 1, 2, 3]. Empty list if not found. + Indices of matches, e.g. [0, 1, 2, 3]. Empty list if not found. """ if len(frac_coord_list) == 0: return [] @@ -234,7 +234,7 @@ def find_in_coord_list_pbc( def in_coord_list_pbc(fcoord_list, fcoord, atol: float = 1e-8, pbc: PbcLike = (True, True, True)) -> bool: - """Tests if a particular fractional coord is within a fractional coord_list. + """Test if a particular fractional coord is within a fractional coord_list. Args: fcoord_list: List of fractional coords to test @@ -250,7 +250,7 @@ def in_coord_list_pbc(fcoord_list, fcoord, atol: float = 1e-8, pbc: PbcLike = (T def is_coord_subset_pbc(subset, superset, atol: float = 1e-8, mask=None, pbc: PbcLike = (True, True, True)) -> bool: - """Tests if all fractional coords in subset are contained in superset. + """Test if all fractional coords in subset are contained in superset. Args: subset (list): List of fractional coords to test @@ -357,7 +357,7 @@ def __init__(self, coords) -> None: """Initialize a Simplex from vertex coordinates. Args: - coords ([[float]]): Coords of the vertices of the simplex. E.g., + coords ([[float]]): Coords of the vertices of the simplex. e.g. [[1, 2, 3], [2, 4, 5], [6, 7, 8], [8, 9, 10]. """ self._coords = np.array(coords) @@ -417,7 +417,7 @@ def in_simplex(self, point: Sequence[float], tolerance: float = 1e-8) -> bool: return (self.bary_coords(point) >= -tolerance).all() def line_intersection(self, point1: Sequence[float], point2: Sequence[float], tolerance: float = 1e-8): - """Computes the intersection points of a line with a simplex. + """Compute the intersection points of a line with a simplex. Args: point1 (Sequence[float]): 1st point to determine the line. diff --git a/pymatgen/util/plotting.py b/pymatgen/util/plotting.py index 3d0f39c414a..be9de10c08c 100644 --- a/pymatgen/util/plotting.py +++ b/pymatgen/util/plotting.py @@ -104,7 +104,7 @@ def pretty_plot_two_axis( height (float): Height of plot in inches. Defaults to width * golden ratio. dpi (int): Sets dot per inch for figure. Defaults to 300. - plot_kwargs: Passthrough kwargs to matplotlib's plot method. E.g., + plot_kwargs: Passthrough kwargs to matplotlib's plot method. e.g. linewidth, etc. Returns: diff --git a/pymatgen/util/provenance.py b/pymatgen/util/provenance.py index 438bc06ef19..cb2469fed00 100644 --- a/pymatgen/util/provenance.py +++ b/pymatgen/util/provenance.py @@ -90,7 +90,7 @@ def from_dict(cls, dct: dict[str, str]) -> Self: @classmethod def parse_history_node(cls, h_node) -> Self: - """Parses a History Node object from either a dict or a tuple. + """Parse a History Node object from either a dict or a tuple. Args: h_node: A dict with name/url/description fields or a 3-element tuple. @@ -134,7 +134,7 @@ def from_dict(cls, dct: dict) -> Self: @classmethod def parse_author(cls, author) -> Self: - """Parses an Author object from either a String, dict, or tuple. + """Parse an Author object from either a String, dict, or tuple. Args: author: A String formatted as "NAME ", diff --git a/pymatgen/util/string.py b/pymatgen/util/string.py index 9fa2c047224..4e63a8e32c8 100644 --- a/pymatgen/util/string.py +++ b/pymatgen/util/string.py @@ -40,8 +40,8 @@ def to_pretty_string(self) -> str: def to_latex_string(self) -> str: """Generate a LaTeX formatted string. The mode is set by the class variable STRING_MODE, which defaults to - "SUBSCRIPT". E.g., Fe2O3 is transformed to Fe$_{2}$O$_{3}$. Setting STRING_MODE to "SUPERSCRIPT" creates - superscript, e.g., Fe2+ becomes Fe^{2+}. The initial string is obtained from the class's __str__ method. + "SUBSCRIPT". e.g. Fe2O3 is transformed to Fe$_{2}$O$_{3}$. Setting STRING_MODE to "SUPERSCRIPT" creates + superscript, e.g. Fe2+ becomes Fe^{2+}. The initial string is obtained from the class's __str__ method. Returns: String for display as in LaTeX with proper superscripts and subscripts. @@ -125,7 +125,7 @@ def formula_double_format(afloat, ignore_ones=True, tol: float = 1e-8): def charge_string(charge, brackets=True, explicit_one=True): """Returns a string representing the charge of an Ion. By default, the - charge is placed in brackets with the sign preceding the magnitude, e.g., + charge is placed in brackets with the sign preceding the magnitude, e.g. '[+2]'. For uncharged species, the string returned is '(aq)'. Args: @@ -146,7 +146,7 @@ def charge_string(charge, brackets=True, explicit_one=True): def latexify(formula: str, bold: bool = False): - """Generate a LaTeX formatted formula. E.g., Fe2O3 is transformed to + """Generate a LaTeX formatted formula. e.g. Fe2O3 is transformed to Fe$_{2}$O$_{3}$. Note that Composition now has a to_latex_string() method that may @@ -195,7 +195,7 @@ def unicodeify(formula: str) -> str: def latexify_spacegroup(spacegroup_symbol): - r"""Generate a latex formatted spacegroup. E.g., P2_1/c is converted to + r"""Generate a latex formatted spacegroup. e.g. P2_1/c is converted to P2$_{1}$/c and P-1 is converted to P$\\overline{1}$. Note that SymmetryGroup now has a to_latex_string() method that may @@ -212,7 +212,7 @@ def latexify_spacegroup(spacegroup_symbol): def unicodeify_spacegroup(spacegroup_symbol): - r"""Generate a unicode formatted spacegroup. E.g., P2$_{1}$/c is converted to + r"""Generate a unicode formatted spacegroup. e.g. P2$_{1}$/c is converted to P2₁/c and P$\\overline{1}$ is converted to P̅1. Note that SymmetryGroup now has a to_unicode_string() method that diff --git a/pymatgen/util/testing/__init__.py b/pymatgen/util/testing/__init__.py index 9acfac56032..8c9ce59233f 100644 --- a/pymatgen/util/testing/__init__.py +++ b/pymatgen/util/testing/__init__.py @@ -63,7 +63,7 @@ def get_structure(cls, name: str) -> Structure: @staticmethod def assert_str_content_equal(actual, expected): - """Tests if two strings are equal, ignoring things like trailing spaces, etc.""" + """Test if two strings are equal, ignoring things like trailing spaces, etc.""" strip_whitespace = {ord(c): None for c in string.whitespace} return actual.translate(strip_whitespace) == expected.translate(strip_whitespace) diff --git a/pymatgen/vis/plotters.py b/pymatgen/vis/plotters.py index 70a89873a42..1692c923562 100644 --- a/pymatgen/vis/plotters.py +++ b/pymatgen/vis/plotters.py @@ -30,7 +30,7 @@ def __init__(self, xshift=0.0, yshift=0.0, stack=False, color_cycle=("qualitativ """ Args: xshift (float): A shift that is applied to the x values. This is - commonly used to shift to an arbitrary zero. E.g., zeroing at the + commonly used to shift to an arbitrary zero. e.g. zeroing at the Fermi energy in DOS, or at the absorption edge in XAS spectra. The same xshift is applied to all spectra. yshift (float): A shift that is applied to the y values. This is @@ -58,7 +58,7 @@ def add_spectrum(self, label, spectrum, color=None): Args: label (str): Label for the Spectrum. Must be unique. spectrum: Spectrum object - color (str): This is passed on to matplotlib. E.g., "k--" indicates + color (str): This is passed on to matplotlib. e.g. "k--" indicates a dashed black line. If None, a color will be chosen based on the default color cycle. """ diff --git a/tests/analysis/chemenv/coordination_environments/test_coordination_geometries.py b/tests/analysis/chemenv/coordination_environments/test_coordination_geometries.py index 8a5d971cd33..3cbda25a5fe 100644 --- a/tests/analysis/chemenv/coordination_environments/test_coordination_geometries.py +++ b/tests/analysis/chemenv/coordination_environments/test_coordination_geometries.py @@ -26,14 +26,14 @@ def __init__(self, coords): class TestCoordinationGeometries(PymatgenTest): def test_algorithms(self): expl_algo = ExplicitPermutationsAlgorithm(permutations=[[0, 1, 2], [1, 2, 3]]) - expl_algo2 = ExplicitPermutationsAlgorithm.from_dict(expl_algo.as_dict) + expl_algo2 = ExplicitPermutationsAlgorithm.from_dict(expl_algo.as_dict()) assert expl_algo.permutations == expl_algo2.permutations sep_plane_algos_oct = all_cg["O:6"].algorithms assert len(sep_plane_algos_oct[0].safe_separation_permutations()) == 24 assert len(sep_plane_algos_oct[1].safe_separation_permutations()) == 36 - sep_plane_algos_oct_0 = SeparationPlane.from_dict(sep_plane_algos_oct[0].as_dict) + sep_plane_algos_oct_0 = SeparationPlane.from_dict(sep_plane_algos_oct[0].as_dict()) assert sep_plane_algos_oct[0].plane_points == sep_plane_algos_oct_0.plane_points assert sep_plane_algos_oct[0].mirror_plane == sep_plane_algos_oct_0.mirror_plane assert sep_plane_algos_oct[0].ordered_plane == sep_plane_algos_oct_0.ordered_plane diff --git a/tests/analysis/elasticity/test_elastic.py b/tests/analysis/elasticity/test_elastic.py index 9916a586a2b..164d4c87918 100644 --- a/tests/analysis/elasticity/test_elastic.py +++ b/tests/analysis/elasticity/test_elastic.py @@ -395,7 +395,7 @@ def test_energy_density(self): class TestDiffFit(PymatgenTest): - """Tests various functions related to diff fitting.""" + """Test various functions related to diff fitting.""" def setUp(self): with open(f"{TEST_DIR}/test_toec_data.json") as file: diff --git a/tests/core/test_sites.py b/tests/core/test_sites.py index 4c6f67d6fa4..a80689d9dfd 100644 --- a/tests/core/test_sites.py +++ b/tests/core/test_sites.py @@ -245,7 +245,7 @@ def get_distance_and_image_old(site1, site2, jimage=None): other site to get distance from. jimage: specific periodic image in terms of lattice translations, - e.g., [1,0,0] implies to take periodic image that is one + e.g. [1,0,0] implies to take periodic image that is one a-lattice vector away. If jimage is None, the image that is nearest to the site is found. diff --git a/tests/io/aims/test_sets/test_input_set.py b/tests/io/aims/test_sets/test_input_set.py index 468b1617b3a..fb7acf5011d 100644 --- a/tests/io/aims/test_sets/test_input_set.py +++ b/tests/io/aims/test_sets/test_input_set.py @@ -28,7 +28,7 @@ # # Suggested "light" defaults for Si atom (to be pasted into control.in file) # Be sure to double-check any results obtained with these settings for post-processing, -# e.g., with the "tight" defaults and larger basis sets. +# e.g. with the "tight" defaults and larger basis sets. # # 2020/09/08 Added f function to "light" after reinspection of Delta test outcomes. # This was done for all of Al-Cl and is a tricky decision since it makes @@ -130,7 +130,7 @@ # # Suggested "light" defaults for Si atom (to be pasted into control.in file) # Be sure to double-check any results obtained with these settings for post-processing, -# e.g., with the "tight" defaults and larger basis sets. +# e.g. with the "tight" defaults and larger basis sets. # # 2020/09/08 Added f function to "light" after reinspection of Delta test outcomes. # This was done for all of Al-Cl and is a tricky decision since it makes diff --git a/tests/io/qchem/test_sets.py b/tests/io/qchem/test_sets.py index 17bcaad3b14..041003d4428 100644 --- a/tests/io/qchem/test_sets.py +++ b/tests/io/qchem/test_sets.py @@ -383,7 +383,7 @@ def test_custom_smd_write(self): os.remove("solvent_data") def test_solvation_warnings(self): - """Tests warnings / errors resulting from nonsensical overwrite_inputs.""" + """Test warnings / errors resulting from nonsensical overwrite_inputs.""" test_molecule = QCInput.from_file(f"{TEST_DIR}/pcm.qin").molecule with pytest.raises(RuntimeError, match="CMIRS is only parameterized"): QChemDictSet(