From be6b6958f0df7b563ebd66a66979c2e2bd1154c6 Mon Sep 17 00:00:00 2001 From: Janosh Riebesell Date: Sat, 16 Sep 2023 16:24:02 +0200 Subject: [PATCH] Breaking: rename `get_ax3d_fig_plt->get_ax3d_fig` and `get_ax_fig_plt->get_ax_fig` plus no longer return `plt` (#3329) * breaking: rename get_ax3d_fig_plt->get_ax3d_fig and stop returning matplotlib.pyplot * breaking: same for get_ax_fig_plt->get_ax_fig * remove :class:`SomeObject` from doc strings probably doesn't work with new markdown docs, can't check without network atm * simplify doc strings: pymatgen.core.(lattice.->'')Lattice * blank line before all Args: and Returns: doc string section headers * use dict.setdefault() instead of checking key presence first * doc string indentation and line break fixes * fix doc string Returns: sections * define reusable LatticeType and CrystalSystem types * simplify with_local_env_strategy() sg.add_edge() call --- pymatgen/alchemy/filters.py | 21 ++- pymatgen/alchemy/transmuters.py | 6 +- pymatgen/analysis/bond_dissociation.py | 2 +- .../connectivity/connected_components.py | 27 ++- .../chemenv_strategies.py | 159 ++++++++++++------ .../coordination_geometries.py | 135 +++++++-------- .../coordination_geometry_finder.py | 8 +- .../structure_environments.py | 102 ++++++----- .../utils/coordination_geometry_utils.py | 14 +- pymatgen/analysis/chemenv/utils/func_utils.py | 24 ++- pymatgen/analysis/diffraction/core.py | 2 +- pymatgen/analysis/dimensionality.py | 6 +- pymatgen/analysis/elasticity/__init__.py | 2 +- pymatgen/analysis/elasticity/elastic.py | 57 ++++--- pymatgen/analysis/energy_models.py | 7 +- pymatgen/analysis/eos.py | 10 +- pymatgen/analysis/functional_groups.py | 5 + pymatgen/analysis/graphs.py | 55 +++--- .../analysis/interfaces/substrate_analyzer.py | 1 + pymatgen/analysis/interfaces/zsl.py | 2 + pymatgen/analysis/local_env.py | 40 +++-- pymatgen/analysis/magnetism/analyzer.py | 48 +++--- pymatgen/analysis/magnetism/jahnteller.py | 9 +- pymatgen/analysis/phase_diagram.py | 5 +- pymatgen/analysis/pourbaix_diagram.py | 8 +- pymatgen/analysis/solar/slme.py | 2 +- pymatgen/analysis/structure_analyzer.py | 4 +- pymatgen/analysis/structure_matcher.py | 1 + pymatgen/analysis/surface_analysis.py | 24 +-- pymatgen/analysis/transition_state.py | 2 +- pymatgen/analysis/wulff.py | 6 +- pymatgen/analysis/xps.py | 1 + pymatgen/apps/borg/hive.py | 4 +- pymatgen/apps/borg/queen.py | 2 +- pymatgen/command_line/critic2_caller.py | 31 ++-- pymatgen/command_line/gulp_caller.py | 2 +- pymatgen/core/bonds.py | 3 +- pymatgen/core/interface.py | 2 +- pymatgen/core/ion.py | 1 + pymatgen/core/lattice.py | 11 +- pymatgen/core/spectrum.py | 8 +- pymatgen/core/structure.py | 44 +++-- pymatgen/core/surface.py | 16 +- .../electronic_structure/bandstructure.py | 7 +- pymatgen/electronic_structure/boltztrap.py | 10 +- pymatgen/electronic_structure/cohp.py | 27 +-- pymatgen/electronic_structure/plotter.py | 75 ++++----- pymatgen/ext/matproj.py | 3 +- pymatgen/ext/optimade.py | 6 +- pymatgen/io/abinit/abiobjects.py | 70 ++++---- pymatgen/io/abinit/abitimer.py | 52 +++--- pymatgen/io/abinit/inputs.py | 2 +- pymatgen/io/abinit/netcdf.py | 4 +- pymatgen/io/abinit/pseudos.py | 46 ++--- pymatgen/io/cif.py | 3 + pymatgen/io/common.py | 2 +- pymatgen/io/cp2k/inputs.py | 7 +- pymatgen/io/exciting/inputs.py | 2 +- pymatgen/io/fiesta.py | 1 + pymatgen/io/lammps/inputs.py | 9 +- pymatgen/io/lmto.py | 5 +- pymatgen/io/lobster/inputs.py | 8 +- pymatgen/io/lobster/lobsterenv.py | 33 ++-- pymatgen/io/lobster/outputs.py | 15 +- pymatgen/io/phonopy.py | 4 +- pymatgen/io/prismatic.py | 5 +- pymatgen/io/res.py | 4 +- pymatgen/io/vasp/inputs.py | 5 + pymatgen/io/vasp/outputs.py | 39 ++--- pymatgen/io/vasp/sets.py | 20 ++- pymatgen/io/xtb/inputs.py | 5 +- pymatgen/phonon/bandstructure.py | 3 +- pymatgen/phonon/gruneisen.py | 3 +- pymatgen/phonon/plotter.py | 32 ++-- pymatgen/phonon/thermal_displacements.py | 42 +++-- pymatgen/symmetry/analyzer.py | 14 +- pymatgen/symmetry/groups.py | 5 +- pymatgen/symmetry/maggroups.py | 4 +- .../advanced_transformations.py | 37 ++-- .../standard_transformations.py | 2 +- pymatgen/util/coord.py | 7 +- pymatgen/util/plotting.py | 30 ++-- tasks.py | 3 +- 83 files changed, 859 insertions(+), 711 deletions(-) diff --git a/pymatgen/alchemy/filters.py b/pymatgen/alchemy/filters.py index 28597a7c27a..b6103de4f70 100644 --- a/pymatgen/alchemy/filters.py +++ b/pymatgen/alchemy/filters.py @@ -59,7 +59,8 @@ def __init__(self, species, strict_compare=False, AND=True, exclude=False): def test(self, structure: Structure): """Method to execute the test. - Returns: True if structure do not contain specified species. + Returns: + bool: True if structure does not contain specified species. """ # set up lists to compare if not self._strict: @@ -139,8 +140,8 @@ def test(self, structure: Structure): Args: structure (Structure): Input structure to test - Returns: True if structure does not contain species within specified - distances. + Returns: + bool: True if structure does not contain species within specified distances. """ all_species = set(self.specie_and_min_dist) for site in structure: @@ -203,7 +204,8 @@ def test(self, structure: Structure): Args: structure (Structure): Input structure to test. - Returns: True if structure is not in list. + Returns: + bool: True if structure is not in list. """ hash = self.structure_matcher._comparator.get_hash(structure.composition) if not self.structure_list[hash]: @@ -253,7 +255,8 @@ def test(self, structure: Structure): Args: structure (Structure): Input structure to test - Returns: True if structure is not in existing list. + Returns: + bool: True if structure is not in existing list. """ def get_sg(s): @@ -297,7 +300,8 @@ def test(self, structure: Structure): Args: structure (Structure): Input structure to test - Returns: True if structure is neutral. + Returns: + bool: True if structure is neutral. """ return structure.charge == 0.0 @@ -329,8 +333,9 @@ def test(self, structure: Structure): Args: structure (Structure): Input structure to test - Returns: True if structure does not contain the two species are distances - greater than max_dist. + Returns: + bool: True if structure does not contain the two species are distances + greater than max_dist. """ sp1_indices = [idx for idx, site in enumerate(structure) if site.specie == self.sp1] sp2_indices = [idx for idx, site in enumerate(structure) if site.specie == self.sp2] diff --git a/pymatgen/alchemy/transmuters.py b/pymatgen/alchemy/transmuters.py index 0a94aa9e9b2..5373623c66b 100644 --- a/pymatgen/alchemy/transmuters.py +++ b/pymatgen/alchemy/transmuters.py @@ -40,11 +40,11 @@ def __init__( self, transformed_structures, transformations=None, - extend_collection=0, - ncores=None, + extend_collection: int = 0, + ncores: int | None = None, ): """Initializes a transmuter from an initial list of - :class:`pymatgen.alchemy.materials.TransformedStructure`. + pymatgen.alchemy.materials.TransformedStructure. Args: transformed_structures ([TransformedStructure]): Input transformed diff --git a/pymatgen/analysis/bond_dissociation.py b/pymatgen/analysis/bond_dissociation.py index 5ce4656107f..f246ae80435 100644 --- a/pymatgen/analysis/bond_dissociation.py +++ b/pymatgen/analysis/bond_dissociation.py @@ -70,7 +70,7 @@ def __init__( raise RuntimeError(key + " must be present in molecule entry! Exiting...") for entry in self.filtered_entries: if key not in entry: - raise RuntimeError(key + " must be present in all fragment entries! Exiting...") + raise RuntimeError(f"{key=} must be present in all fragment entries! Exiting...") # Define expected charges final_charge = int(molecule_entry["final_molecule"]["charge"]) # type: ignore[index] diff --git a/pymatgen/analysis/chemenv/connectivity/connected_components.py b/pymatgen/analysis/chemenv/connectivity/connected_components.py index e85cba06cc9..a5f3bba8e73 100644 --- a/pymatgen/analysis/chemenv/connectivity/connected_components.py +++ b/pymatgen/analysis/chemenv/connectivity/connected_components.py @@ -27,9 +27,6 @@ def draw_network(env_graph, pos, ax, sg=None, periodicity_vectors=None): ax: Axes object in which the network should be drawn. sg: Not used currently (drawing of supergraphs). periodicity_vectors: List of periodicity vectors that should be drawn. - - Returns: None - """ for n in env_graph: c = Circle(pos[n], radius=0.02, alpha=0.5) @@ -124,18 +121,18 @@ def draw_network(env_graph, pos, ax, sg=None, periodicity_vectors=None): def make_supergraph(graph, multiplicity, periodicity_vectors): - """Make supergraph from a graph of environments. + """Make super graph from a graph of environments. Args: graph: Graph of environments. - multiplicity: Multiplicity of the supergraph. - periodicity_vectors: Periodicity vectors needed to make the supergraph. - - Returns: Super graph of the environments. + multiplicity: Multiplicity of the super graph. + periodicity_vectors: Periodicity vectors needed to make the super graph. + Returns: + nx.MultiGraph: Super graph of the environments. """ - supergraph = nx.MultiGraph() - print("peridoicity vectors :") + super_graph = nx.MultiGraph() + print("periodicity vectors :") print(periodicity_vectors) if isinstance(multiplicity, int) or len(multiplicity) == 1: mult = multiplicity if isinstance(multiplicity, int) else multiplicity[0] @@ -173,25 +170,25 @@ def make_supergraph(graph, multiplicity, periodicity_vectors): new_data = dict(data) new_data["start"] = (imult * len(nodes)) + indices_nodes[n1] new_data["end"] = (imult * len(nodes)) + indices_nodes[n2] - supergraph.add_edge(new_data["start"], new_data["end"], key=key, attr_dict=new_data) + super_graph.add_edge(new_data["start"], new_data["end"], key=key, attr_dict=new_data) for n1, n2, key, data in connecting_edges: new_data = dict(data) new_data["start"] = (imult * len(nodes)) + indices_nodes[n1] new_data["end"] = np.mod(((imult + 1) * len(nodes)) + indices_nodes[n2], len(nodes) * mult) new_data["delta"] = (0, 0, 0) - supergraph.add_edge(new_data["start"], new_data["end"], key=key, attr_dict=new_data) + super_graph.add_edge(new_data["start"], new_data["end"], key=key, attr_dict=new_data) imult = mult - 1 for n1, n2, key, data in other_edges: new_data = dict(data) new_data["start"] = (imult * len(nodes)) + indices_nodes[n1] new_data["end"] = (imult * len(nodes)) + indices_nodes[n2] - supergraph.add_edge(new_data["start"], new_data["end"], key=key, attr_dict=new_data) + super_graph.add_edge(new_data["start"], new_data["end"], key=key, attr_dict=new_data) for n1, n2, key, data in connecting_edges: new_data = dict(data) new_data["start"] = (imult * len(nodes)) + indices_nodes[n1] new_data["end"] = indices_nodes[n2] - supergraph.add_edge(new_data["start"], new_data["end"], key=key, attr_dict=new_data) - return supergraph + super_graph.add_edge(new_data["start"], new_data["end"], key=key, attr_dict=new_data) + return super_graph raise NotImplementedError("make_supergraph not yet implemented for 2- and 3-periodic graphs") diff --git a/pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py b/pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py index c5f0f899b63..8938b88f839 100644 --- a/pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py +++ b/pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py @@ -237,6 +237,7 @@ def equivalent_site_index_and_transform(self, psite): """Get the equivalent site and corresponding symmetry+translation transformations. :param psite: Periodic site. + Returns: Equivalent site in the unit cell, translations and symmetry transformation. """ @@ -318,6 +319,7 @@ def get_site_neighbors(self, site): def uniquely_determines_coordination_environments(self): """ Returns True if the strategy leads to a unique coordination environment, False otherwise. + Returns: True if the strategy leads to a unique coordination environment, False otherwise. """ @@ -447,6 +449,7 @@ def __str__(self): def as_dict(self): """ Bson-serializable dict representation of the SimplestChemenvStrategy object. + Returns: Bson-serializable dict representation of the SimplestChemenvStrategy object. """ @@ -591,6 +594,7 @@ def get_site_neighbors(self, site, isite=None, dequivsite=None, dthissite=None, :param dequivsite: Translation of the equivalent site. :param dthissite: Translation of this site. :param mysym: Symmetry to be applied. + Returns: List of coordinated neighbors of site. """ @@ -633,6 +637,7 @@ def get_site_coordination_environment( :param dthissite: Translation of this site. :param mysym: Symmetry to be applied. :param return_map: Whether to return cn_map (identifies the NeighborsSet used). + Returns: Coordination environment of site. """ @@ -717,6 +722,7 @@ def get_site_coordination_environments_fractions( :param min_fraction: Minimum fraction to include in the list :param return_maps: Whether to return cn_maps (identifies all the NeighborsSet used). :param return_strategy_dict_info: Whether to add the info about the strategy used. + Returns: List of Dict with coordination environment, fraction and additional info. """ @@ -767,6 +773,7 @@ def get_site_coordination_environments( :param dthissite: Translation of this site. :param mysym: Symmetry to be applied. :param return_maps: Whether to return cn_maps (identifies all the NeighborsSet used). + Returns: List of coordination environment. """ @@ -802,6 +809,7 @@ def __eq__(self, other: object) -> bool: def as_dict(self): """ Bson-serializable dict representation of the SimplestChemenvStrategy object. + Returns: Bson-serializable dict representation of the SimplestChemenvStrategy object. """ @@ -882,6 +890,7 @@ def get_site_neighbors(self, site): """Get the neighbors of a given site with this strategy. :param site: Periodic site. + Returns: List of neighbors of site. """ @@ -912,6 +921,7 @@ def get_site_coordination_environment( :param dthissite: Translation of this site. :param mysym: Symmetry to be applied. :param return_map: Whether to return cn_map (identifies the NeighborsSet used). + Returns: Coordination environment of site. """ @@ -952,6 +962,7 @@ def get_site_coordination_environments( :param dthissite: Translation of this site. :param mysym: Symmetry to be applied. :param return_maps: Whether to return cn_maps (identifies all the NeighborsSet used). + Returns: List of coordination environment. """ @@ -1000,6 +1011,7 @@ def __eq__(self, other: object) -> bool: def as_dict(self): """ Bson-serializable dict representation of the SimpleAbundanceChemenvStrategy object. + Returns: Bson-serializable dict representation of the SimpleAbundanceChemenvStrategy object. """ @@ -1084,6 +1096,7 @@ def get_site_coordination_environment( :param dthissite: Translation of this site. :param mysym: Symmetry to be applied. :param return_map: Whether to return cn_map (identifies the NeighborsSet used). + Returns: Coordination environment of site. """ @@ -1150,6 +1163,7 @@ def uniquely_determines_coordination_environments(self): def as_dict(self): """ Bson-serializable dict representation of the TargettedPenaltiedAbundanceChemenvStrategy object. + Returns: Bson-serializable dict representation of the TargettedPenaltiedAbundanceChemenvStrategy object. """ @@ -1209,6 +1223,7 @@ def weight(self, nb_set, structure_environments, cn_map=None, additional_info=No :param structure_environments: Structure environments used to estimate weight. :param cn_map: Mapping index for this neighbors set. :param additional_info: Additional information. + Returns: Weight of the neighbors set. """ @@ -1237,6 +1252,7 @@ def weight(self, nb_set, structure_environments, cn_map=None, additional_info=No :param structure_environments: Structure environments used to estimate weight. :param cn_map: Mapping index for this neighbors set. :param additional_info: Additional information. + Returns: Weight of the neighbors set. """ @@ -1247,6 +1263,7 @@ def angle_sum(nb_set): """Sum of all angles in a neighbors set. :param nb_set: Neighbors set. + Returns: Sum of solid angles for the neighbors set. """ @@ -1256,6 +1273,7 @@ def angle_sumn(self, nb_set): """Sum of all angles to a given power in a neighbors set. :param nb_set: Neighbors set. + Returns: Sum of solid angles to the power aa for the neighbors set. """ @@ -1275,12 +1293,9 @@ def as_dict(self): } @classmethod - def from_dict(cls, dd): - """ - From dict - :param dd: - """ - return cls(aa=dd["aa"]) + def from_dict(cls, dct): + """Construct AngleNbSetWeight from dict representation.""" + return cls(aa=dct["aa"]) class NormalizedAngleDistanceNbSetWeight(NbSetWeight): @@ -1341,20 +1356,22 @@ def as_dict(self): } @classmethod - def from_dict(cls, dd): + def from_dict(cls, dct): """Initialize from dict. - :param dd: Dict representation of NormalizedAngleDistanceNbSetWeight. + :param dct: Dict representation of NormalizedAngleDistanceNbSetWeight. + Returns: NormalizedAngleDistanceNbSetWeight. """ - return cls(average_type=dd["average_type"], aa=dd["aa"], bb=dd["bb"]) + return cls(average_type=dct["average_type"], aa=dct["aa"], bb=dct["bb"]) @staticmethod def invdist(nb_set): """Inverse distance weight. :param nb_set: Neighbors set. + Returns: List of inverse distances. """ @@ -1364,6 +1381,7 @@ def invndist(self, nb_set): """Inverse power distance weight. :param nb_set: Neighbors set. + Returns: List of inverse power distances. """ @@ -1374,6 +1392,7 @@ def ang(nb_set): """Angle weight. :param nb_set: Neighbors set. + Returns: List of angle weights. """ @@ -1383,6 +1402,7 @@ def angn(self, nb_set): """Power angle weight. :param nb_set: Neighbors set. + Returns: List of power angle weights. """ @@ -1393,6 +1413,7 @@ def anginvdist(nb_set): """Angle/distance weight. :param nb_set: Neighbors set. + Returns: List of angle/distance weights. """ @@ -1403,6 +1424,7 @@ def anginvndist(self, nb_set): """Angle/power distance weight. :param nb_set: Neighbors set. + Returns: List of angle/power distance weights. """ @@ -1413,6 +1435,7 @@ def angninvdist(self, nb_set): """Power angle/distance weight. :param nb_set: Neighbors set. + Returns: List of power angle/distance weights. """ @@ -1423,6 +1446,7 @@ def angninvndist(self, nb_set): """Power angle/power distance weight. :param nb_set: Neighbors set. + Returns: List of power angle/power distance weights. """ @@ -1436,6 +1460,7 @@ def weight(self, nb_set, structure_environments, cn_map=None, additional_info=No :param structure_environments: Structure environments used to estimate weight. :param cn_map: Mapping index for this neighbors set. :param additional_info: Additional information. + Returns: Weight of the neighbors set. """ @@ -1447,6 +1472,7 @@ def gweight(fda_list): """Geometric mean of the weights. :param fda_list: List of estimator weights for each neighbor. + Returns: Geometric mean of the weights. """ @@ -1457,6 +1483,7 @@ def aweight(fda_list): """Standard mean of the weights. :param fda_list: List of estimator weights for each neighbor. + Returns: Standard mean of the weights. """ @@ -1575,6 +1602,7 @@ def weight(self, nb_set, structure_environments, cn_map=None, additional_info=No :param structure_environments: Structure environments used to estimate weight. :param cn_map: Mapping index for this neighbors set. :param additional_info: Additional information. + Returns: Weight of the neighbors set. """ @@ -1618,17 +1646,18 @@ def as_dict(self): } @classmethod - def from_dict(cls, dd): + def from_dict(cls, dct): """Initialize from dict. - :param dd: Dict representation of SelfCSMNbSetWeight. + :param dct: Dict representation of SelfCSMNbSetWeight. + Returns: SelfCSMNbSetWeight. """ return cls( - effective_csm_estimator=dd["effective_csm_estimator"], - weight_estimator=dd["weight_estimator"], - symmetry_measure_type=dd["symmetry_measure_type"], + effective_csm_estimator=dct["effective_csm_estimator"], + weight_estimator=dct["weight_estimator"], + symmetry_measure_type=dct["symmetry_measure_type"], ) @@ -1681,6 +1710,7 @@ def weight(self, nb_set, structure_environments, cn_map=None, additional_info=No :param structure_environments: Structure environments used to estimate weight. :param cn_map: Mapping index for this neighbors set. :param additional_info: Additional information. + Returns: Weight of the neighbors set. """ @@ -1797,6 +1827,7 @@ def delta_cn_specifics( :param function: Ratio function used. :param symmetry_measure_type: Type of symmetry measure to be used. :param effective_csm_estimator: Ratio function used for the effective CSM (comparison between neighbors sets). + Returns: DeltaCSMNbSetWeight. """ @@ -1849,22 +1880,23 @@ def as_dict(self): } @classmethod - def from_dict(cls, dd): + def from_dict(cls, dct): """Initialize from dict. - :param dd: Dict representation of DeltaCSMNbSetWeight. + :param dct: Dict representation of DeltaCSMNbSetWeight. + Returns: DeltaCSMNbSetWeight. """ return cls( - effective_csm_estimator=dd["effective_csm_estimator"], - weight_estimator=dd["weight_estimator"], + effective_csm_estimator=dct["effective_csm_estimator"], + weight_estimator=dct["weight_estimator"], delta_cn_weight_estimators={ - int(dcn): dcn_estimator for dcn, dcn_estimator in dd["delta_cn_weight_estimators"].items() + int(dcn): dcn_estimator for dcn, dcn_estimator in dct["delta_cn_weight_estimators"].items() } - if dd.get("delta_cn_weight_estimators") is not None + if dct.get("delta_cn_weight_estimators") is not None else None, - symmetry_measure_type=dd["symmetry_measure_type"], + symmetry_measure_type=dct["symmetry_measure_type"], ) @@ -1889,6 +1921,7 @@ def weight(self, nb_set, structure_environments, cn_map=None, additional_info=No :param structure_environments: Structure environments used to estimate weight. :param cn_map: Mapping index for this neighbors set. :param additional_info: Additional information. + Returns: Weight of the neighbors set. """ @@ -1913,16 +1946,17 @@ def as_dict(self): } @classmethod - def from_dict(cls, dd): + def from_dict(cls, dct): """Initialize from dict. - :param dd: Dict representation of CNBiasNbSetWeight. + :param dct: Dict representation of CNBiasNbSetWeight. + Returns: CNBiasNbSetWeight. """ return cls( - cn_weights={int(cn): cnw for cn, cnw in dd["cn_weights"].items()}, - initialization_options=dd["initialization_options"], + cn_weights={int(cn): cnw for cn, cnw in dct["cn_weights"].items()}, + initialization_options=dct["initialization_options"], ) @classmethod @@ -1931,6 +1965,7 @@ def linearly_equidistant(cls, weight_cn1, weight_cn13): :param weight_cn1: Weight of coordination 1. :param weight_cn13: Weight of coordination 13. + Returns: CNBiasNbSetWeight. """ @@ -1949,6 +1984,7 @@ def geometrically_equidistant(cls, weight_cn1, weight_cn13): :param weight_cn1: Weight of coordination 1. :param weight_cn13: Weight of coordination 13. + Returns: CNBiasNbSetWeight. """ @@ -1966,6 +2002,7 @@ def explicit(cls, cn_weights): """Initializes weights explicitly for each coordination. :param cn_weights: Weights for each coordination. + Returns: CNBiasNbSetWeight. """ @@ -1975,19 +2012,20 @@ def explicit(cls, cn_weights): return cls(cn_weights=cn_weights, initialization_options=initialization_options) @classmethod - def from_description(cls, dd): + def from_description(cls, dct): """Initializes weights from description. - :param dd: Dictionary description. + :param dct: Dictionary description. + Returns: CNBiasNbSetWeight. """ - if dd["type"] == "linearly_equidistant": - return cls.linearly_equidistant(weight_cn1=dd["weight_cn1"], weight_cn13=dd["weight_cn13"]) - if dd["type"] == "geometrically_equidistant": - return cls.geometrically_equidistant(weight_cn1=dd["weight_cn1"], weight_cn13=dd["weight_cn13"]) - if dd["type"] == "explicit": - return cls.explicit(cn_weights=dd["cn_weights"]) + if dct["type"] == "linearly_equidistant": + return cls.linearly_equidistant(weight_cn1=dct["weight_cn1"], weight_cn13=dct["weight_cn13"]) + if dct["type"] == "geometrically_equidistant": + return cls.geometrically_equidistant(weight_cn1=dct["weight_cn1"], weight_cn13=dct["weight_cn13"]) + if dct["type"] == "explicit": + return cls.explicit(cn_weights=dct["cn_weights"]) return None @@ -2058,6 +2096,7 @@ def weight(self, nb_set, structure_environments, cn_map=None, additional_info=No :param structure_environments: Structure environments used to estimate weight. :param cn_map: Mapping index for this neighbors set. :param additional_info: Additional information. + Returns: Weight of the neighbors set. """ @@ -2075,6 +2114,7 @@ def w_area_has_intersection(self, nb_set, structure_environments, cn_map, additi :param structure_environments: Structure environments. :param cn_map: Mapping index of the neighbors set. :param additional_info: Additional information. + Returns: Area intersection between neighbors set and surface. """ @@ -2092,6 +2132,7 @@ def w_area_intersection_nbsfh_fbs_onb0(self, nb_set, structure_environments, cn_ :param structure_environments: Structure environments. :param cn_map: Mapping index of the neighbors set. :param additional_info: Additional information. + Returns: Area intersection between neighbors set and surface. """ @@ -2205,19 +2246,20 @@ def as_dict(self): } @classmethod - def from_dict(cls, dd): + def from_dict(cls, dct): """Initialize from dict. - :param dd: Dict representation of DistanceAngleAreaNbSetWeight. + :param dct: Dict representation of DistanceAngleAreaNbSetWeight. + Returns: DistanceAngleAreaNbSetWeight. """ return cls( - weight_type=dd["weight_type"], - surface_definition=dd["surface_definition"], - nb_sets_from_hints=dd["nb_sets_from_hints"], - other_nb_sets=dd["other_nb_sets"], - additional_condition=dd["additional_condition"], + weight_type=dct["weight_type"], + surface_definition=dct["surface_definition"], + nb_sets_from_hints=dct["nb_sets_from_hints"], + other_nb_sets=dct["other_nb_sets"], + additional_condition=dct["additional_condition"], ) @@ -2252,6 +2294,7 @@ def weight(self, nb_set, structure_environments, cn_map=None, additional_info=No :param structure_environments: Structure environments used to estimate weight. :param cn_map: Mapping index for this neighbors set. :param additional_info: Additional information. + Returns: Weight of the neighbors set. """ @@ -2273,16 +2316,17 @@ def as_dict(self): } @classmethod - def from_dict(cls, dd): + def from_dict(cls, dct): """Initialize from dict. - :param dd: Dict representation of DistancePlateauNbSetWeight. + :param dct: Dict representation of DistancePlateauNbSetWeight. + Returns: DistancePlateauNbSetWeight. """ return cls( - distance_function=dd["distance_function"], - weight_function=dd["weight_function"], + distance_function=dct["distance_function"], + weight_function=dct["weight_function"], ) @@ -2317,6 +2361,7 @@ def weight(self, nb_set, structure_environments, cn_map=None, additional_info=No :param structure_environments: Structure environments used to estimate weight. :param cn_map: Mapping index for this neighbors set. :param additional_info: Additional information. + Returns: Weight of the neighbors set. """ @@ -2338,14 +2383,15 @@ def as_dict(self): } @classmethod - def from_dict(cls, dd): + def from_dict(cls, dct): """Initialize from dict. - :param dd: Dict representation of AnglePlateauNbSetWeight. + :param dct: Dict representation of AnglePlateauNbSetWeight. + Returns: AnglePlateauNbSetWeight. """ - return cls(angle_function=dd["angle_function"], weight_function=dd["weight_function"]) + return cls(angle_function=dct["angle_function"], weight_function=dct["weight_function"]) class DistanceNbSetWeight(NbSetWeight): @@ -2378,6 +2424,7 @@ def weight(self, nb_set, structure_environments, cn_map=None, additional_info=No :param structure_environments: Structure environments used to estimate weight. :param cn_map: Mapping index for this neighbors set. :param additional_info: Additional information. + Returns: Weight of the neighbors set. """ @@ -2417,14 +2464,15 @@ def as_dict(self): } @classmethod - def from_dict(cls, dd): + def from_dict(cls, dct): """Initialize from dict. - :param dd: Dict representation of DistanceNbSetWeight. + :param dct: Dict representation of DistanceNbSetWeight. + Returns: DistanceNbSetWeight. """ - return cls(weight_function=dd["weight_function"], nbs_source=dd["nbs_source"]) + return cls(weight_function=dct["weight_function"], nbs_source=dct["nbs_source"]) class DeltaDistanceNbSetWeight(NbSetWeight): @@ -2457,6 +2505,7 @@ def weight(self, nb_set, structure_environments, cn_map=None, additional_info=No :param structure_environments: Structure environments used to estimate weight. :param cn_map: Mapping index for this neighbors set. :param additional_info: Additional information. + Returns: Weight of the neighbors set. """ @@ -2499,14 +2548,15 @@ def as_dict(self): } @classmethod - def from_dict(cls, dd): + def from_dict(cls, dct): """Initialize from dict. - :param dd: Dict representation of DeltaDistanceNbSetWeight. + :param dct: Dict representation of DeltaDistanceNbSetWeight. + Returns: DeltaDistanceNbSetWeight. """ - return cls(weight_function=dd["weight_function"], nbs_source=dd["nbs_source"]) + return cls(weight_function=dct["weight_function"], nbs_source=dct["nbs_source"]) class WeightedNbSetChemenvStrategy(AbstractChemenvStrategy): @@ -2572,6 +2622,7 @@ def get_site_coordination_environments_fractions( :param min_fraction: Minimum fraction to include in the list :param return_maps: Whether to return cn_maps (identifies all the NeighborsSet used). :param return_strategy_dict_info: Whether to add the info about the strategy used. + Returns: List of Dict with coordination environment, fraction and additional info. """ @@ -2739,6 +2790,7 @@ def get_site_coordination_environments( :param dthissite: Translation of this site. :param mysym: Symmetry to be applied. :param return_maps: Whether to return cn_maps (identifies all the NeighborsSet used). + Returns: List of coordination environment. """ @@ -2772,6 +2824,7 @@ def __ne__(self, other): def as_dict(self): """ Bson-serializable dict representation of the WeightedNbSetChemenvStrategy object. + Returns: Bson-serializable dict representation of the WeightedNbSetChemenvStrategy object. """ diff --git a/pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py b/pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py index bc80a9de621..1870c91ac75 100644 --- a/pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py +++ b/pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py @@ -58,7 +58,8 @@ def algorithm_type(self): """ Return the type of algorithm. - Returns: Type of the algorithm + Returns: + str: Type of the algorithm """ return self._algorithm_type @@ -74,8 +75,7 @@ class ExplicitPermutationsAlgorithm(AbstractChemenvAlgorithm): """ def __init__(self, permutations): - """ - Initializes a separation plane for a given perfect coordination geometry. + """Initializes a separation plane for a given perfect coordination geometry. Args: permutations: Permutations used for this algorithm. @@ -91,16 +91,16 @@ def permutations(self): """ Return the permutations to be performed for this algorithm. - Returns: Permutations to be performed. + Returns: + list: Permutations to be performed. """ return self._permutations @property def as_dict(self): """ - Return the JSON-serializable dict representation of this ExplicitPermutationsAlgorithm algorithm. - - Returns: a JSON-serializable dict representation of this ExplicitPermutationsAlgorithm algorithm. + Returns: + dict: JSON-serializable representation of this ExplicitPermutationsAlgorithm """ return { "@module": type(self).__module__, @@ -109,16 +109,11 @@ def as_dict(self): } @classmethod - def from_dict(cls, dd): + def from_dict(cls, dct): """ - Reconstructs the ExplicitPermutationsAlgorithm algorithm from its JSON-serializable dict representation. - - Args: - dd: a JSON-serializable dict representation of an ExplicitPermutationsAlgorithm algorithm. - - Returns: an ExplicitPermutationsAlgorithm algorithm. + Reconstruct ExplicitPermutationsAlgorithm from its JSON-serializable dict representation. """ - return cls(dd["permutations"]) + return cls(dct["permutations"]) class SeparationPlane(AbstractChemenvAlgorithm): @@ -141,8 +136,7 @@ def __init__( multiplicity=None, other_plane_points=None, ): - """ - Initializes a separation plane for a given perfect coordination geometry. + """Initializes a separation plane for a given perfect coordination geometry. Args: plane_points: Indices of the points that are in the plane in the perfect structure (and should be @@ -202,7 +196,8 @@ def permutations(self): """ Permutations used for this separation plane algorithm. - Returns: List of permutations to be performed. + Returns: + list[Permutations]: to be performed. """ return self._permutations @@ -212,11 +207,12 @@ def ref_separation_perm(self): 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]. + 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 of ordered indices of this separation plane. + Returns: + list[int]: of ordered indices of this separation plane. """ return self._ref_separation_perm @@ -227,7 +223,8 @@ def argsorted_ref_separation_perm(self): This is used in the identification of the final permutation to be used. - Returns: list of the "arg sorted" ordered indices of the separation plane. + Returns: + list[int]: "arg sorted" ordered indices of the separation plane. """ return self._argsorted_ref_separation_perm @@ -244,7 +241,8 @@ def safe_separation_permutations(self, ordered_plane=False, ordered_point_groups number of permutations. add_opposite: Whether to add the permutations from the second group before the first group as well. - Returns: List of safe permutations. + Returns + list[int]: safe permutations. """ s0 = list(range(len(self.point_groups[0]))) plane = list( @@ -303,7 +301,8 @@ def as_dict(self): """ Return the JSON-serializable dict representation of this SeparationPlane algorithm. - Returns: a JSON-serializable dict representation of this SeparationPlane algorithm. + Returns: + dict: JSON-serializable representation of this SeparationPlane algorithm. """ return { "@module": type(self).__module__, @@ -330,9 +329,10 @@ def from_dict(cls, dct): Reconstructs the SeparationPlane algorithm from its JSON-serializable dict representation. Args: - dd: a JSON-serializable dict representation of an SeparationPlane algorithm. + dct: a JSON-serializable dict representation of an SeparationPlane algorithm. - Returns: a SeparationPlane algorithm. + Returns: + SeparationPlane: algorithm object """ eop = [np.array(eo_perm) for eo_perm in dct.get("explicit_optimized_permutations", [])] or None return cls( @@ -373,8 +373,7 @@ class NeighborsSetsHints: ALLOWED_HINTS_TYPES = ("single_cap", "double_cap", "triple_cap") def __init__(self, hints_type, options): - """ - Constructor for this NeighborsSetsHints. + """Constructor for this NeighborsSetsHints. Args: hints_type: type of hint (single, double or triple cap) @@ -387,28 +386,28 @@ def __init__(self, hints_type, options): self.options = options def hints(self, hints_info): - """ - Return hints for an additional neighbors set, i.e. the voronoi indices that constitute this new - neighbors set. + """Return hints for an additional neighbors set, i.e. the voronoi indices that + constitute this new neighbors set. Args: hints_info: Info needed to build new "hinted" neighbors set. - Returns: Voronoi indices of the new "hinted" neighbors set. + Returns: + list[int]: Voronoi indices of the new "hinted" neighbors set. """ if hints_info["csm"] > self.options["csm_max"]: return [] return object.__getattribute__(self, f"{self.hints_type}_hints")(hints_info) def single_cap_hints(self, hints_info): - """ - Return hints for an additional neighbors set, i.e. the voronoi indices that constitute this new - neighbors set, in case of a "Single cap" hint. + """Return hints for an additional neighbors set, i.e. the voronoi indices that + constitute this new neighbors set, in case of a "Single cap" hint. Args: hints_info: Info needed to build new "hinted" neighbors set. - Returns: Voronoi indices of the new "hinted" neighbors set. + Returns: + list[int]: Voronoi indices of the new "hinted" neighbors set. """ cap_index_perfect = self.options["cap_index"] nb_set = hints_info["nb_set"] @@ -420,14 +419,14 @@ def single_cap_hints(self, hints_info): return [new_site_voronoi_indices] def double_cap_hints(self, hints_info): - """ - Return hints for an additional neighbors set, i.e. the voronoi indices that constitute this new - neighbors set, in case of a "Double cap" hint. + """Return hints for an additional neighbors set, i.e. the voronoi indices that + constitute this new neighbors set, in case of a "Double cap" hint. Args: hints_info: Info needed to build new "hinted" neighbors set. - Returns: Voronoi indices of the new "hinted" neighbors set. + Returns: + list[int]: Voronoi indices of the new "hinted" neighbors set. """ first_cap_index_perfect = self.options["first_cap_index"] second_cap_index_perfect = self.options["second_cap_index"] @@ -446,14 +445,14 @@ def double_cap_hints(self, hints_info): return new_site_voronoi_indices1, new_site_voronoi_indices2, new_site_voronoi_indices3 def triple_cap_hints(self, hints_info): - """ - Return hints for an additional neighbors set, i.e. the voronoi indices that constitute this new - neighbors set, in case of a "Triple cap" hint. + """Return hints for an additional neighbors set, i.e. the voronoi indices that + constitute this new neighbors set, in case of a "Triple cap" hint. Args: hints_info: Info needed to build new "hinted" neighbors set. - Returns: Voronoi indices of the new "hinted" neighbors set. + Returns: + list[int]: Voronoi indices of the new "hinted" neighbors set. """ first_cap_index_perfect = self.options["first_cap_index"] second_cap_index_perfect = self.options["second_cap_index"] @@ -498,16 +497,9 @@ def as_dict(self): return {"hints_type": self.hints_type, "options": self.options} @classmethod - def from_dict(cls, dd): - """ - Reconstructs the NeighborsSetsHints from its JSON-serializable dict representation. - - Args: - dd: a JSON-serializable dict representation of a NeighborsSetsHints. - - Returns: a NeighborsSetsHints. - """ - return cls(hints_type=dd["hints_type"], options=dd["options"]) + def from_dict(cls, dct): + """Reconstructs the NeighborsSetsHints from its JSON-serializable dict representation.""" + return cls(hints_type=dct["hints_type"], options=dct["options"]) def __init__( self, @@ -607,7 +599,8 @@ def from_dict(cls, dct): Args: dct: a JSON-serializable dict representation of a CoordinationGeometry. - Returns: a CoordinationGeometry. + Returns: + CoordinationGeometry """ dec = MontyDecoder() return cls( @@ -700,11 +693,7 @@ def set_permutations_safe_override(self, permutations_safe_override): @property def distfactor_max(self): - """ - The maximum distfactor for the perfect CoordinationGeometry. - - Returns: Maximum distfactor for the perfect CoordinationGeometry (usually 1.0 for symmetric polyhedrons). - """ + """The maximum distfactor for the perfect CoordinationGeometry (usually 1.0 for symmetric polyhedrons).""" dists = [np.linalg.norm(pp - self.central_site) for pp in self.points] return np.max(dists) / np.min(dists) @@ -720,16 +709,16 @@ def pauling_stability_ratio(self): if self.ce_symbol in ["S:1", "L:2"]: self._pauling_stability_ratio = 0.0 else: - mindist_anions = 1000000.0 - mindist_cation_anion = 1000000.0 + min_dist_anions = 1000000.0 + min_dist_cation_anion = 1000000.0 for ipt1 in range(len(self.points)): # pylint: disable=C0200 pt1 = np.array(self.points[ipt1]) - mindist_cation_anion = min(mindist_cation_anion, np.linalg.norm(pt1 - self.central_site)) + min_dist_cation_anion = min(min_dist_cation_anion, np.linalg.norm(pt1 - self.central_site)) for ipt2 in range(ipt1 + 1, len(self.points)): pt2 = np.array(self.points[ipt2]) - mindist_anions = min(mindist_anions, np.linalg.norm(pt1 - pt2)) - anion_radius = mindist_anions / 2.0 - cation_radius = mindist_cation_anion - anion_radius + min_dist_anions = min(min_dist_anions, np.linalg.norm(pt1 - pt2)) + anion_radius = min_dist_anions / 2.0 + cation_radius = min_dist_cation_anion - anion_radius self._pauling_stability_ratio = cation_radius / anion_radius return self._pauling_stability_ratio @@ -793,7 +782,8 @@ def ref_permutation(self, permutation): Args: permutation: Current permutation - Returns: Reference permutation of the perfect CoordinationGeometry. + Returns: + Permutation: Reference permutation of the perfect CoordinationGeometry. """ perms = [] for eqv_indices in self.equivalent_indices: @@ -1019,7 +1009,8 @@ def get_symbol_name_mapping(self, coordination=None): Args: coordination: Whether to restrict the dictionary to a given coordination. - Returns: Dictionary mapping the symbol of a CoordinationGeometry to its name. + Returns: + dict: map symbol of a CoordinationGeometry to its name. """ geom = {} if coordination is None: @@ -1038,7 +1029,8 @@ def get_symbol_cn_mapping(self, coordination=None): Args: coordination: Whether to restrict the dictionary to a given coordination. - Returns: Dictionary mapping the symbol of a CoordinationGeometry to its coordination. + Returns: + dict: map of symbol of a CoordinationGeometry to its coordination. """ geom = {} if coordination is None: @@ -1218,7 +1210,8 @@ def pretty_print(self, type="implemented_geometries", maxcn=8, additional_info=N maxcn: Maximum coordination. additional_info: Whether to add some additional info for each coordination geometry. - Returns: String describing the list of coordination geometries. + Returns: + str: description of the list of coordination geometries. """ if type == "all_geometries_latex_images": output = "" diff --git a/pymatgen/analysis/chemenv/coordination_environments/coordination_geometry_finder.py b/pymatgen/analysis/chemenv/coordination_environments/coordination_geometry_finder.py index 862e230f953..f1a11d60158 100644 --- a/pymatgen/analysis/chemenv/coordination_environments/coordination_geometry_finder.py +++ b/pymatgen/analysis/chemenv/coordination_environments/coordination_geometry_finder.py @@ -154,7 +154,7 @@ def __str__(self): String representation of the AbstractGeometry Returns: - String representation of the AbstractGeometry. + str: String representation of the AbstractGeometry. """ outs = [f"\nAbstract Geometry with {len(self.coords)} points :"] for pp in self.coords: @@ -468,6 +468,7 @@ def get_structure(self): """ Returns the pymatgen Structure that has been setup for the identification of geometries (the initial one might have been refined/symmetrized using the SpaceGroupAnalyzer). + Returns: The pymatgen Structure that has been setup for the identification of geometries (the initial one might have been refined/symmetrized using the SpaceGroupAnalyzer). @@ -761,8 +762,7 @@ def compute_structure_environments( optimization=optimization, ) t_nbset2 = time.process_time() - if cn not in nb_sets_info: - nb_sets_info[cn] = {} + nb_sets_info.setdefault(cn, {}) nb_sets_info[cn][inb_set] = {"time": t_nbset2 - t_nbset1} if get_from_hints: for cg_symbol, cg_dict in ce: @@ -1120,6 +1120,7 @@ def setup_explicit_indices_local_geometry(self, 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. + Returns: the continuous symmetry measures of the current local geometry in a dictionary. """ @@ -1249,6 +1250,7 @@ def get_coordination_symmetry_measures_optim( ): """ Returns 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. """ diff --git a/pymatgen/analysis/chemenv/coordination_environments/structure_environments.py b/pymatgen/analysis/chemenv/coordination_environments/structure_environments.py index 9cf133dbfe1..23d77215f9b 100644 --- a/pymatgen/analysis/chemenv/coordination_environments/structure_environments.py +++ b/pymatgen/analysis/chemenv/coordination_environments/structure_environments.py @@ -46,8 +46,7 @@ class NeighborsSet: """Class used to store a given set of neighbors of a given site (based on the detailed_voronoi).""" def __init__(self, structure: Structure, isite, detailed_voronoi, site_voronoi_indices, sources=None): - """ - Constructor for NeighborsSet. + """Constructor for NeighborsSet. Args: structure: Structure object. @@ -73,13 +72,13 @@ def __init__(self, structure: Structure, isite, detailed_voronoi, site_voronoi_i self.sources = [sources] def get_neighb_voronoi_indices(self, permutation): - """ - Return the indices in the detailed_voronoi corresponding to the current permutation. + """Get indices in the detailed_voronoi corresponding to the current permutation. Args: permutation: Current permutation for which the indices in the detailed_voronoi are needed. - Returns: List of indices in the detailed_voronoi. + Returns: + list[int]: indices in the detailed_voronoi. """ return [self.site_voronoi_indices[ii] for ii in permutation] @@ -286,8 +285,7 @@ def voronoi_grid_surface_points(self, additional_condition=1, other_origins="DO_ ia1 = a1_indices[0] ia2 = a2_indices[0] for id_ia in [(id1, ia1), (id1, ia2), (id2, ia1), (id2, ia2)]: - if id_ia not in points_dict: - points_dict[id_ia] = 0 + points_dict.setdefault(id_ia, 0) points_dict[id_ia] += 1 new_pts = [] @@ -325,8 +323,8 @@ def voronoi_grid_surface_points(self, additional_condition=1, other_origins="DO_ @property def source(self): """ - Returns the source of this NeighborsSet (how it was generated, e.g. from which Voronoi cut-offs, or from - hints). + Returns the source of this NeighborsSet (how it was generated, e.g. from which Voronoi + cutoffs, or from hints). """ if len(self.sources) != 1: raise RuntimeError("Number of sources different from 1 !") @@ -370,7 +368,7 @@ def as_dict(self): } @classmethod - def from_dict(cls, dd, structure: Structure, detailed_voronoi): + def from_dict(cls, dct, structure: Structure, detailed_voronoi): """ Reconstructs the NeighborsSet algorithm from its JSON-serializable dict representation, together with the structure and the DetailedVoronoiContainer. @@ -380,19 +378,20 @@ def from_dict(cls, dd, structure: Structure, detailed_voronoi): reconstructing itself. These two are both in the StructureEnvironments object. Args: - dd: a JSON-serializable dict representation of a NeighborsSet. + dct: a JSON-serializable dict representation of a NeighborsSet. structure: The structure. detailed_voronoi: The Voronoi object containing all the neighboring atoms from which the subset of neighbors for this NeighborsSet is extracted. - Returns: a NeighborsSet. + Returns: + NeighborsSet """ return cls( structure=structure, - isite=dd["isite"], + isite=dct["isite"], detailed_voronoi=detailed_voronoi, - site_voronoi_indices=dd["site_voronoi_indices"], - sources=dd["sources"], + site_voronoi_indices=dct["site_voronoi_indices"], + sources=dct["sources"], ) def __init__( @@ -584,7 +583,8 @@ def get_coordination_environments(self, isite, cn, nb_set): cn: Coordination for which the ChemicalEnvironments is looked for. nb_set: Neighbors set for which the ChemicalEnvironments is looked for. - Returns: a ChemicalEnvironments object. + Returns: + ChemicalEnvironments """ if self.ce_list[isite] is None: return None @@ -604,7 +604,8 @@ def get_csm(self, isite, mp_symbol): isite: Index of the site. mp_symbol: Symbol of the coordination environment for which we want the continuous symmetry measure. - Returns: Continuous symmetry measure of the given site in the given environment. + Returns: + Continuous symmetry measure of the given site in the given environment. """ csms = self.get_csms(isite, mp_symbol) if len(csms) != 1: @@ -615,7 +616,7 @@ def get_csm(self, isite, mp_symbol): ) return csms[0] - def get_csms(self, isite, mp_symbol): + def get_csms(self, isite, mp_symbol) -> list: """ Returns 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 @@ -629,7 +630,7 @@ def get_csms(self, isite, mp_symbol): mp_symbol: MP symbol of the perfect environment for which the csm has to be given. Returns: - List of csms for site isite with respect to geometry mp_symbol + list[CSM]: for site isite with respect to geometry mp_symbol """ cn = symbol_cn_mapping[mp_symbol] if cn not in self.ce_list[isite]: @@ -1384,8 +1385,7 @@ class NeighborsSet: """ def __init__(self, structure: Structure, isite, all_nbs_sites, all_nbs_sites_indices): - """ - Constructor for NeighborsSet. + """Constructor for NeighborsSet. Args: structure: Structure object. @@ -1463,7 +1463,7 @@ def as_dict(self): } @classmethod - def from_dict(cls, dd, structure: Structure, all_nbs_sites): + def from_dict(cls, dct, structure: Structure, all_nbs_sites): """ Reconstructs the NeighborsSet algorithm from its JSON-serializable dict representation, together with the structure and all the possible neighbors sites. @@ -1473,17 +1473,18 @@ def from_dict(cls, dd, structure: Structure, all_nbs_sites): reconstructing itself. These two are both in the LightStructureEnvironments object. Args: - dd: a JSON-serializable dict representation of a NeighborsSet. + dct: a JSON-serializable dict representation of a NeighborsSet. structure: The structure. all_nbs_sites: The list of all the possible neighbors for a given site. - Returns: a NeighborsSet. + Returns: + NeighborsSet """ return cls( structure=structure, - isite=dd["isite"], + isite=dct["isite"], all_nbs_sites=all_nbs_sites, - all_nbs_sites_indices=dd["all_nbs_sites_indices"], + all_nbs_sites_indices=dct["all_nbs_sites_indices"], ) def __init__( @@ -1530,7 +1531,8 @@ def from_structure_environments(cls, strategy, structure_environments, valences= valences_origin: How the valences were obtained (e.g. from the Bond-valence analysis or from the original structure). - Returns: a LightStructureEnvironments object. + Returns: + LightStructureEnvironments """ structure = structure_environments.structure strategy.set_structure_environments(structure_environments=structure_environments) @@ -1650,18 +1652,18 @@ def setup_statistic_lists(self): valence = self.valences[isite] strspecie = str(Species(sp.symbol, valence)) if valence < 0: - specielist = self.statistics_dict["anion_list"] + specie_list = self.statistics_dict["anion_list"] atomlist = self.statistics_dict["anion_atom_list"] elif valence > 0: - specielist = self.statistics_dict["cation_list"] + specie_list = self.statistics_dict["cation_list"] atomlist = self.statistics_dict["cation_atom_list"] else: - specielist = self.statistics_dict["neutral_list"] + specie_list = self.statistics_dict["neutral_list"] atomlist = self.statistics_dict["neutral_atom_list"] - if strspecie not in specielist: - specielist[strspecie] = occ + if strspecie not in specie_list: + specie_list[strspecie] = occ else: - specielist[strspecie] += occ + specie_list[strspecie] += occ if sp.symbol not in atomlist: atomlist[sp.symbol] = occ else: @@ -1676,8 +1678,7 @@ def setup_statistic_lists(self): for ce_symbol, fraction in site_envs: if fraction is None: continue - if ce_symbol not in count_ce: - count_ce[ce_symbol] = 0.0 + count_ce.setdefault(ce_symbol, 0.0) count_ce[ce_symbol] += fraction for sp, occ in site.species.items(): elmt = sp.symbol @@ -1762,8 +1763,10 @@ def get_site_info_for_specie_ce(self, specie, ce_symbol): specie: Species to get. ce_symbol: Symbol of the coordination environment to get. - Returns: Dictionary with the list of indices in the structure that have the given specie in the given - environment, their fraction and continuous symmetry measures. + Returns: + dict: Keys are 'isites', 'fractions', 'csms' which contain list of indices in the structure + that have the given specie in the given environment, their fraction and continuous + symmetry measures. """ element = specie.symbol oxi_state = specie.oxi_state @@ -1789,8 +1792,9 @@ def get_site_info_for_specie_allces(self, specie, min_fraction=0): specie: Species to get. min_fraction: Minimum fraction of the coordination environment. - Returns: Dictionary with the list of coordination environments for the given species, the indices of the sites - in which they appear, their fractions and continuous symmetry measures. + Returns: + dict: with the list of coordination environments for the given species, the indices of the sites + in which they appear, their fractions and continuous symmetry measures. """ allces = {} element = specie.symbol @@ -1826,7 +1830,7 @@ def get_statistics(self, statistics_fields=DEFAULT_STATISTICS_FIELDS, bson_compa bson_compatible: Whether to make the dictionary BSON-compatible. Returns: - A dictionary with the requested statistics. + dict: with the requested statistics. """ if self.statistics_dict is None: self.setup_statistic_lists() @@ -1845,7 +1849,8 @@ def contains_only_one_anion_atom(self, anion_atom): Args: anion_atom: Anion (e.g. O, ...). The structure could contain O2- and O- though. - Returns: True if this LightStructureEnvironments concerns a structure with only one given anion_atom. + Returns: + bool: True if this LightStructureEnvironments concerns a structure with only one given anion_atom. """ return ( len(self.statistics_dict["anion_atom_list"]) == 1 and anion_atom in self.statistics_dict["anion_atom_list"] @@ -1858,7 +1863,8 @@ def contains_only_one_anion(self, anion): Args: anion: Anion (e.g. O2-, ...). - Returns: True if this LightStructureEnvironments concerns a structure with only one given anion. + Returns: + bool: True if this LightStructureEnvironments concerns a structure with only one given anion. """ return len(self.statistics_dict["anion_list"]) == 1 and anion in self.statistics_dict["anion_list"] @@ -1870,7 +1876,8 @@ def site_contains_environment(self, isite, ce_symbol): isite: Index of the site. ce_symbol: Symbol of the coordination environment. - Returns: True if the site contains the given coordination environment. + Returns: + bool: True if the site contains the given coordination environment. """ if self.coordination_environments[isite] is None: return False @@ -1887,7 +1894,8 @@ def site_has_clear_environment(self, isite, conditions=None): isite: Index of the site. conditions: Conditions to be checked for an environment to be "clear". - Returns: True if the site has a clear environment. + Returns: + bool: True if the site has a clear environment. """ if self.coordination_environments[isite] is None: raise ValueError(f"Coordination environments have not been determined for site {isite}") @@ -1941,7 +1949,8 @@ def clear_environments(self, conditions=None): Args: conditions: Conditions to be checked for an environment to be "clear". - Returns: Set of clear environments in this structure. + Returns: + list: Clear environments in this structure. """ clear_envs_list = set() for isite in range(len(self.structure)): @@ -1979,7 +1988,8 @@ def environments_identified(self): """ Return the set of environments identified in this structure. - Returns: Set of environments identified in this structure. + Returns: + set: environments identified in this structure. """ return {ce["ce_symbol"] for celist in self.coordination_environments if celist is not None for ce in celist} diff --git a/pymatgen/analysis/chemenv/utils/coordination_geometry_utils.py b/pymatgen/analysis/chemenv/utils/coordination_geometry_utils.py index fbf2ebe7048..f8b6223fa24 100644 --- a/pymatgen/analysis/chemenv/utils/coordination_geometry_utils.py +++ b/pymatgen/analysis/chemenv/utils/coordination_geometry_utils.py @@ -392,8 +392,7 @@ def vectorsToMatrix(aa, bb): :param bb: Another vector of size 3 Returns: - A 3x3 matrix M composed of the products of the elements of aa and bb : - M_ij = aa_i * bb_j. + A 3x3 matrix M composed of the products of the elements of aa and bb : M_ij = aa_i * bb_j. """ MM = np.zeros([3, 3], np.float_) for ii in range(3): @@ -730,6 +729,7 @@ def indices_separate(self, points, dist_tolerance): :param points: list of points :param dist_tolerance: tolerance to which a point is considered to lie on the plane or not (distance to the plane) + Returns: The lists of indices of the points on one side of the plane, on the plane and on the other side of the plane. @@ -888,6 +888,7 @@ def fit_error(self, points, fit="least_square_distance"): :param points: List of points. :param fit: Type of fit error. + Returns: Error for a list of points with respect to this plane. """ @@ -901,6 +902,7 @@ def fit_least_square_distance_error(self, points): """Evaluate the sum of squared distances error for a list of points with respect to this plane. :param points: List of points. + Returns: Sum of squared distances error for a list of points with respect to this plane. """ @@ -910,6 +912,7 @@ def fit_maximum_distance_error(self, points): """Evaluate the max distance error for a list of points with respect to this plane. :param points: List of points. + Returns: Max distance error for a list of points with respect to this plane. """ @@ -974,6 +977,7 @@ def from_2points_and_origin(cls, p1, p2): :param p1: First point. :param p2: Second point. + Returns: Plane. """ @@ -986,6 +990,7 @@ def from_3points(cls, p1, p2, p3): :param p1: First point. :param p2: Second point. :param p3: Third point. + Returns: Plane. """ @@ -1006,6 +1011,7 @@ def from_npoints(cls, points, best_fit="least_square_distance"): :param points: List of points. :param best_fit: Type of fitting procedure for more than 3 points. + Returns: Plane """ @@ -1024,6 +1030,7 @@ def from_npoints_least_square_distance(cls, points): """Initializes plane from a list of points using a least square fitting procedure. :param points: List of points. + Returns: Plane. """ @@ -1052,6 +1059,7 @@ def perpendicular_bisector(cls, p1, p2): :param p1: First point. :param p2: Second point. + Returns: Plane. """ @@ -1065,6 +1073,7 @@ def from_npoints_maximum_distance(cls, points): """Initializes plane from a list of points using a max distance fitting procedure. :param points: List of points. + Returns: Plane. """ @@ -1096,6 +1105,7 @@ def from_coefficients(cls, a, b, c, d): :param b: b coefficient of the plane. :param c: c coefficient of the plane. :param d: d coefficient of the plane. + Returns: Plane. """ diff --git a/pymatgen/analysis/chemenv/utils/func_utils.py b/pymatgen/analysis/chemenv/utils/func_utils.py index 2b178e32f69..30837721ad5 100644 --- a/pymatgen/analysis/chemenv/utils/func_utils.py +++ b/pymatgen/analysis/chemenv/utils/func_utils.py @@ -89,21 +89,22 @@ def evaluate(self, value): """Evaluate the ratio function for the given value. :param value: Value for which ratio function has to be evaluated. + Returns: Ratio function corresponding to the value. """ return self.eval(value) @classmethod - def from_dict(cls, dd): + def from_dict(cls, dct): """Construct ratio function from dict. - :param dd: Dict representation of the ratio function + :param dct: Dict representation of the ratio function Returns: Ratio function object. """ - return cls(function=dd["function"], options_dict=dd["options"]) + return cls(function=dct["function"], options_dict=dct["options"]) class RatioFunction(AbstractRatioFunction): @@ -126,6 +127,7 @@ def power2_decreasing_exp(self, vals): correspond to the "alpha" parameter. :param vals: Values for which the ratio function has to be evaluated. + Returns: Result of the ratio function applied to the values. """ @@ -137,6 +139,7 @@ def smootherstep(self, vals): The values (i.e. "x"), are scaled between the "lower" and "upper" parameters. :param vals: Values for which the ratio function has to be evaluated. + Returns: Result of the ratio function applied to the values. """ @@ -148,6 +151,7 @@ def smoothstep(self, vals): The values (i.e. "x"), are scaled between the "lower" and "upper" parameters. :param vals: Values for which the ratio function has to be evaluated. + Returns: Result of the ratio function applied to the values. """ @@ -159,6 +163,7 @@ def inverse_smootherstep(self, vals): The values (i.e. "x"), are scaled between the "lower" and "upper" parameters. :param vals: Values for which the ratio function has to be evaluated. + Returns: Result of the ratio function applied to the values. """ @@ -170,6 +175,7 @@ def inverse_smoothstep(self, vals): The values (i.e. "x"), are scaled between the "lower" and "upper" parameters. :param vals: Values for which the ratio function has to be evaluated. + Returns: Result of the ratio function applied to the values. """ @@ -181,6 +187,7 @@ def power2_inverse_decreasing(self, vals): The values (i.e. "x"), are scaled to the "max" parameter. :param vals: Values for which the ratio function has to be evaluated. + Returns: Result of the ratio function applied to the values. """ @@ -192,6 +199,7 @@ def power2_inverse_power2_decreasing(self, vals): The values (i.e. "x"), are scaled to the "max" parameter. :param vals: Values for which the ratio function has to be evaluated. + Returns: Result of the ratio function applied to the values. """ @@ -221,6 +229,7 @@ def power2_decreasing_exp(self, vals): correspond to the "alpha" parameter. :param vals: CSM values for which the ratio function has to be evaluated. + Returns: Result of the ratio function applied to the CSM values. """ @@ -232,6 +241,7 @@ def smootherstep(self, vals): The CSM values (i.e. "x"), are scaled between the "lower_csm" and "upper_csm" parameters. :param vals: CSM values for which the ratio function has to be evaluated. + Returns: Result of the ratio function applied to the CSM values. """ @@ -247,6 +257,7 @@ def smoothstep(self, vals): The CSM values (i.e. "x"), are scaled between the "lower_csm" and "upper_csm" parameters. :param vals: CSM values for which the ratio function has to be evaluated. + Returns: Result of the ratio function applied to the CSM values. """ @@ -260,6 +271,7 @@ def fractions(self, data): """Get the fractions from the CSM ratio function applied to the data. :param data: List of CSM values to estimate fractions. + Returns: Corresponding fractions for each CSM. """ @@ -274,6 +286,7 @@ def mean_estimator(self, data): """Get the weighted CSM using this CSM ratio function applied to the data. :param data: List of CSM values to estimate the weighted CSM. + Returns: Weighted CSM from this ratio function. """ @@ -311,6 +324,7 @@ def power2_inverse_decreasing(self, vals): correspond to the "alpha" parameter. :param vals: CSM values for which the ratio function has to be evaluated. + Returns: Result of the ratio function applied to the CSM values. """ @@ -323,6 +337,7 @@ def power2_inverse_power2_decreasing(self, vals): correspond to the "alpha" parameter. :param vals: CSM values for which the ratio function has to be evaluated. + Returns: Result of the ratio function applied to the CSM values. """ @@ -332,6 +347,7 @@ def fractions(self, data): """Get the fractions from the CSM ratio function applied to the data. :param data: List of CSM values to estimate fractions. + Returns: Corresponding fractions for each CSM. """ @@ -355,6 +371,7 @@ def mean_estimator(self, data): """Get the weighted CSM using this CSM ratio function applied to the data. :param data: List of CSM values to estimate the weighted CSM. + Returns: Weighted CSM from this ratio function. """ @@ -390,6 +407,7 @@ def smootherstep(self, vals): The DeltaCSM values (i.e. "x"), are scaled between the "delta_csm_min" and "delta_csm_max" parameters. :param vals: DeltaCSM values for which the ratio function has to be evaluated. + Returns: Result of the ratio function applied to the DeltaCSM values. """ diff --git a/pymatgen/analysis/diffraction/core.py b/pymatgen/analysis/diffraction/core.py index cb9cd6af503..5e156a7120e 100644 --- a/pymatgen/analysis/diffraction/core.py +++ b/pymatgen/analysis/diffraction/core.py @@ -92,7 +92,7 @@ def get_plot( with hkl indices. Default is 'compact', i.e. show short version (oriented vertically), e.g. 100. If 'full', show long version, e.g. (1, 0, 0). If None, do not show anything. - ax: matplotlib :class:`Axes` or None if a new figure should be + ax: matplotlib Axes or None if a new figure should be created. with_labels: True to add xlabels and ylabels to the plot. fontsize: (int) fontsize for peak labels. diff --git a/pymatgen/analysis/dimensionality.py b/pymatgen/analysis/dimensionality.py index 33ccb1dad85..ead8cc9f544 100644 --- a/pymatgen/analysis/dimensionality.py +++ b/pymatgen/analysis/dimensionality.py @@ -525,9 +525,9 @@ def get_dimensionality_gorai( and the max bonding distance. For example, PO4 groups may be defined as {("P", "O"): 3}. - Returns: (int) the dimensionality of the structure - 1 (molecules/chains), - 2 (layered), or 3 (3D) - + Returns: + int: the dimensionality of the structure - 1 (molecules/chains), + 2 (layered), or 3 (3D) """ if standardize: structure = SpacegroupAnalyzer(structure).get_conventional_standard_structure() diff --git a/pymatgen/analysis/elasticity/__init__.py b/pymatgen/analysis/elasticity/__init__.py index f2758b4315e..787fa643c21 100644 --- a/pymatgen/analysis/elasticity/__init__.py +++ b/pymatgen/analysis/elasticity/__init__.py @@ -13,7 +13,7 @@ get_diff_coeff, get_strain_state_dict, get_symbol_list, - raise_error_if_unphysical, + raise_if_unphysical, subs, ) from .strain import Deformation, DeformedStructureSet, Strain diff --git a/pymatgen/analysis/elasticity/elastic.py b/pymatgen/analysis/elasticity/elastic.py index 4eee805ab83..ca190558b49 100644 --- a/pymatgen/analysis/elasticity/elastic.py +++ b/pymatgen/analysis/elasticity/elastic.py @@ -105,24 +105,16 @@ def from_diff_fit(cls, strains, stresses, eq_stress=None, order=2, tol: float = return cls(diff_fit(strains, stresses, eq_stress, order, tol)[order - 2]) -def raise_error_if_unphysical(f): +def raise_if_unphysical(func): """ Wrapper for functions or properties that should raise an error if tensor is unphysical. """ def wrapper(self, *args, **kwargs): - """ - Args: - self (): - *args (): - **kwargs (): - - Returns: - """ if self.k_vrh < 0 or self.g_vrh < 0: raise ValueError("Bulk or shear modulus is negative, property cannot be determined") - return f(self, *args, **kwargs) + return func(self, *args, **kwargs) return wrapper @@ -229,7 +221,7 @@ def directional_elastic_mod(self, n): n = get_uvec(n) return self.einsum_sequence([n] * 4) - @raise_error_if_unphysical + @raise_if_unphysical def trans_v(self, structure: Structure): """ Calculates transverse sound velocity (in SI units) using the @@ -238,7 +230,8 @@ def trans_v(self, structure: Structure): Args: structure: pymatgen structure object - Returns: transverse sound velocity (in SI units) + Returns: + float: transverse sound velocity (in SI units) """ n_sites = len(structure) volume = structure.volume @@ -249,7 +242,7 @@ def trans_v(self, structure: Structure): raise ValueError("k_vrh or g_vrh is negative, sound velocity is undefined") return (1e9 * self.g_vrh / mass_density) ** 0.5 - @raise_error_if_unphysical + @raise_if_unphysical def long_v(self, structure: Structure): """ Calculates longitudinal sound velocity (in SI units) @@ -258,7 +251,8 @@ def long_v(self, structure: Structure): Args: structure: pymatgen structure object - Returns: longitudinal sound velocity (in SI units) + Returns: + float: longitudinal sound velocity (in SI units) """ n_sites = len(structure) volume = structure.volume @@ -269,7 +263,7 @@ def long_v(self, structure: Structure): raise ValueError("k_vrh or g_vrh is negative, sound velocity is undefined") return (1e9 * (self.k_vrh + 4 / 3 * self.g_vrh) / mass_density) ** 0.5 - @raise_error_if_unphysical + @raise_if_unphysical def snyder_ac(self, structure: Structure): """ Calculates Snyder's acoustic sound velocity (in SI units). @@ -277,7 +271,8 @@ def snyder_ac(self, structure: Structure): Args: structure: pymatgen structure object - Returns: Snyder's acoustic sound velocity (in SI units) + Returns: + float: Snyder's acoustic sound velocity (in SI units) """ n_sites = len(structure) volume = structure.volume @@ -292,15 +287,16 @@ def snyder_ac(self, structure: Structure): / (300 * num_density ** (-2 / 3) * n_sites ** (1 / 3)) ) - @raise_error_if_unphysical + @raise_if_unphysical def snyder_opt(self, structure: Structure): """ Calculates Snyder's optical sound velocity (in SI units). Args: - structure: pymatgen structure object + structure: pymatgen Structure object - Returns: Snyder's optical sound velocity (in SI units) + Returns: + float: Snyder's optical sound velocity (in SI units) """ n_sites = len(structure) volume = structure.volume @@ -313,7 +309,7 @@ def snyder_opt(self, structure: Structure): * (1 - n_sites ** (-1 / 3)) ) - @raise_error_if_unphysical + @raise_if_unphysical def snyder_total(self, structure: Structure): """ Calculates Snyder's total sound velocity (in SI units). @@ -321,11 +317,12 @@ def snyder_total(self, structure: Structure): Args: structure: pymatgen structure object - Returns: Snyder's total sound velocity (in SI units) + Returns: + float: Snyder's total sound velocity (in SI units) """ return self.snyder_ac(structure) + self.snyder_opt(structure) - @raise_error_if_unphysical + @raise_if_unphysical def clarke_thermalcond(self, structure: Structure): """ Calculates Clarke's thermal conductivity (in SI units). @@ -333,7 +330,8 @@ def clarke_thermalcond(self, structure: Structure): Args: structure: pymatgen structure object - Returns: Clarke's thermal conductivity (in SI units) + Returns: + float: Clarke's thermal conductivity (in SI units) """ n_sites = len(structure) volume = structure.volume @@ -344,7 +342,7 @@ def clarke_thermalcond(self, structure: Structure): mass_density = 1.6605e3 * n_sites * weight / (n_atoms * volume) return 0.87 * 1.3806e-23 * avg_mass ** (-2 / 3) * mass_density ** (1 / 6) * self.y_mod**0.5 - @raise_error_if_unphysical + @raise_if_unphysical def cahill_thermalcond(self, structure: Structure): """ Calculates Cahill's thermal conductivity (in SI units). @@ -352,23 +350,25 @@ def cahill_thermalcond(self, structure: Structure): Args: structure: pymatgen structure object - Returns: Cahill's thermal conductivity (in SI units) + Returns: + float: Cahill's thermal conductivity (in SI units) """ n_sites = len(structure) volume = structure.volume num_density = 1e30 * n_sites / volume return 1.3806e-23 / 2.48 * num_density ** (2 / 3) * (self.long_v(structure) + 2 * self.trans_v(structure)) - @raise_error_if_unphysical + @raise_if_unphysical def debye_temperature(self, structure: Structure): """ - Estimates the debye temperature from longitudinal and + Estimates the Debye temperature from longitudinal and transverse sound velocities. Args: structure: pymatgen structure object - Returns: debye temperature (in SI units) + Returns: + float: debye temperature (in SI units) """ v0 = structure.volume * 1e-30 / len(structure) vl, vt = self.long_v(structure), self.trans_v(structure) @@ -468,6 +468,7 @@ def from_pseudoinverse(cls, strains, stresses): def from_independent_strains(cls, strains, stresses, eq_stress=None, vasp=False, tol: float = 1e-10): """ Constructs the elastic tensor least-squares fit of independent strains + Args: strains (list of Strains): list of strain objects to fit stresses (list of Stresses): list of stress objects to use in fit diff --git a/pymatgen/analysis/energy_models.py b/pymatgen/analysis/energy_models.py index c27917da21c..756fb384d43 100644 --- a/pymatgen/analysis/energy_models.py +++ b/pymatgen/analysis/energy_models.py @@ -51,7 +51,7 @@ class EwaldElectrostaticModel(EnergyModel): 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 - :class:`pymatgen.analysis.ewald.EwaldSummation`. + pymatgen.analysis.ewald.EwaldSummation. Args: real_space_cut (float): Real space cutoff radius dictating how @@ -104,11 +104,10 @@ def as_dict(self): class SymmetryModel(EnergyModel): """ - Sets the energy to the -ve of the spacegroup number. Higher symmetry => + Sets the energy to the negative of the spacegroup number. Higher symmetry => lower "energy". - Args have same meaning as in - :class:`pymatgen.symmetry.finder.SpacegroupAnalyzer`. + Args have same meaning as in pymatgen.symmetry.SpacegroupAnalyzer. """ def __init__(self, symprec: float = 0.1, angle_tolerance=5): diff --git a/pymatgen/analysis/eos.py b/pymatgen/analysis/eos.py index 92db505747b..4c331802b98 100644 --- a/pymatgen/analysis/eos.py +++ b/pymatgen/analysis/eos.py @@ -17,7 +17,7 @@ from scipy.optimize import leastsq, minimize from pymatgen.core.units import FloatWithUnit -from pymatgen.util.plotting import add_fig_kwargs, get_ax_fig_plt, pretty_plot +from pymatgen.util.plotting import add_fig_kwargs, get_ax_fig, pretty_plot if TYPE_CHECKING: from matplotlib import pyplot as plt @@ -108,7 +108,7 @@ def func(self, volume): to the ones obtained from fitting. Args: - volume (list/numpy.array) + volume (list/numpy.array) Returns: numpy.array @@ -223,7 +223,7 @@ def plot_ax(self, ax: plt.Axes = None, fontsize=12, **kwargs): Plot the equation of state on axis `ax`. Args: - ax: matplotlib :class:`Axes` or None if a new figure should be created. + ax: matplotlib Axes or None if a new figure should be created. fontsize: Legend fontsize. color (str): plot color. label (str): Plot label @@ -233,7 +233,7 @@ def plot_ax(self, ax: plt.Axes = None, fontsize=12, **kwargs): plt.Figure: matplotlib figure. """ # pylint: disable=E1307 - ax, fig, plt = get_ax_fig_plt(ax=ax) + ax, fig = get_ax_fig(ax=ax) color = kwargs.get("color", "r") label = kwargs.get("label", f"{type(self).__name__} fit") @@ -349,7 +349,7 @@ def fit(self, order): Do polynomial fitting and set the parameters. Uses numpy polyfit. Args: - order (int): order of the fit polynomial + order (int): order of the fit polynomial """ self.eos_params = np.polyfit(self.volumes, self.energies, order) self._set_params() diff --git a/pymatgen/analysis/functional_groups.py b/pymatgen/analysis/functional_groups.py index 5aad2631d68..a82a6f95a6a 100644 --- a/pymatgen/analysis/functional_groups.py +++ b/pymatgen/analysis/functional_groups.py @@ -102,6 +102,7 @@ def get_heteroatoms(self, elements=None): :param elements: List of elements to identify (if only certain functional groups are of interest). + Returns: set of ints representing node indices """ @@ -132,6 +133,7 @@ def get_special_carbon(self, elements=None): :param elements: List of elements that will qualify a carbon as special (if only certain functional groups are of interest). Default None. + Returns: set of ints representing node indices """ @@ -197,6 +199,7 @@ def link_marked_atoms(self, atoms): :param atoms: set of marked "interesting" atoms, presumably identified using other functions in this class. + Returns: list of sets of ints, representing groups of connected atoms """ @@ -233,6 +236,7 @@ def get_basic_functional_groups(self, func_groups=None): :param func_groups: List of strs representing the functional groups of interest. Default to None, meaning that all of the functional groups defined in this function will be sought. + Returns: list of sets of ints, representing groups of connected atoms """ @@ -316,6 +320,7 @@ def categorize_functional_groups(self, groups): Determine classes of functional groups present in a set. :param groups: Set of functional groups. + Returns: dict containing representations of the groups, the indices of where the group occurs in the MoleculeGraph, and how many of each diff --git a/pymatgen/analysis/graphs.py b/pymatgen/analysis/graphs.py index 6fcb1fcb0f9..7eeead9e905 100644 --- a/pymatgen/analysis/graphs.py +++ b/pymatgen/analysis/graphs.py @@ -198,6 +198,7 @@ def with_edges(structure, edges): where props is a dictionary of properties, including weight. Props should be None if no additional properties are to be specified. + Returns: sg, a StructureGraph """ @@ -242,11 +243,11 @@ def with_edges(structure, edges): def with_local_env_strategy(structure, strategy, weights=False, edge_properties=False): """ Constructor for StructureGraph, using a strategy - from :class:`pymatgen.analysis.local_env`. + from pymatgen.analysis.local_env. :param structure: Structure object :param strategy: an instance of a - :class:`pymatgen.analysis.local_env.NearNeighbors` object + pymatgen.analysis.local_env.NearNeighbors object :param weights: if True, use weights from local_env class (consult relevant class for their meaning) :param edge_properties: if True, edge_properties from neighbors will be used @@ -262,26 +263,15 @@ def with_local_env_strategy(structure, strategy, weights=False, edge_properties= # for any one bond, one from site u to site v # and another form site v to site u: this is # harmless, so warn_duplicates=False - if edge_properties: - sg.add_edge( - from_index=idx, - from_jimage=(0, 0, 0), - to_index=neighbor["site_index"], - to_jimage=neighbor["image"], - weight=neighbor["weight"] if weights else None, - edge_properties=neighbor["edge_properties"], - warn_duplicates=False, - ) - else: - sg.add_edge( - from_index=idx, - from_jimage=(0, 0, 0), - to_index=neighbor["site_index"], - to_jimage=neighbor["image"], - weight=neighbor["weight"] if weights else None, - edge_properties=None, - warn_duplicates=False, - ) + sg.add_edge( + from_index=idx, + from_jimage=(0, 0, 0), + to_index=neighbor["site_index"], + to_jimage=neighbor["image"], + weight=neighbor["weight"] if weights else None, + edge_properties=neighbor["edge_properties"] if edge_properties else None, + warn_duplicates=False, + ) return sg @@ -379,10 +369,7 @@ def add_edge( return # sanitize types - from_jimage, to_jimage = ( - tuple(map(int, from_jimage)), - tuple(map(int, to_jimage)), - ) + from_jimage, to_jimage = tuple(map(int, from_jimage)), tuple(map(int, to_jimage)) from_index, to_index = int(from_index), int(to_index) # if edge is from site i to site i, constrain direction of edge @@ -1006,6 +993,7 @@ def types_of_coordination_environments(self, anonymous=False): :param anonymous: if anonymous, will replace specie names with A, B, C, etc. + Returns: a list of co-ordination environments, e.g. ['Mo-S(6)', 'S-Mo(3)'] @@ -1042,7 +1030,7 @@ def types_of_coordination_environments(self, anonymous=False): def as_dict(self): """ - As in :class:`pymatgen.core.Structure` except + As in pymatgen.core.Structure except with using `to_dict_of_dicts` from NetworkX to store graph information. """ @@ -1056,7 +1044,7 @@ def as_dict(self): @classmethod def from_dict(cls, d): """ - As in :class:`pymatgen.core.Structure` except + As in pymatgen.core.Structure except restoring graphs using `from_dict_of_dicts` from NetworkX to restore graph information. """ @@ -1624,6 +1612,7 @@ def with_edges(molecule: Molecule, edges: dict[tuple[int, int], dict]): group (format: {(u, v): props}, where props is a dictionary of properties, including weight. Props should be None if no additional properties are to be specified. + Returns: mg, a MoleculeGraph """ @@ -1658,11 +1647,11 @@ def with_edges(molecule: Molecule, edges: dict[tuple[int, int], dict]): def with_local_env_strategy(molecule, strategy): """ Constructor for MoleculeGraph, using a strategy - from :class:`pymatgen.analysis.local_env`. + from pymatgen.analysis.local_env. :param molecule: Molecule object :param strategy: an instance of a - :class:`pymatgen.analysis.local_env.NearNeighbors` object + pymatgen.analysis.local_env.NearNeighbors object Returns: mg, a MoleculeGraph @@ -2038,6 +2027,7 @@ def split_molecule_subgraphs(self, bonds, allow_reverse=False, alterations=None) :param allow_reverse: If allow_reverse is True, then break_edge will attempt to break both (from_index, to_index) and, failing that, will attempt to break (to_index, from_index). + Returns: list of MoleculeGraphs. """ @@ -2606,7 +2596,7 @@ def draw_graph_to_file( def as_dict(self): """ - As in :class:`pymatgen.core.Molecule` except + As in pymatgen.core.Molecule except with using `to_dict_of_dicts` from NetworkX to store graph information. """ @@ -2618,7 +2608,7 @@ def as_dict(self): @classmethod def from_dict(cls, dct): """ - As in :class:`pymatgen.core.Molecule` except + As in pymatgen.core.Molecule except restoring graphs using `from_dict_of_dicts` from NetworkX to restore graph information. """ @@ -2744,6 +2734,7 @@ def isomorphic_to(self, other): graphs are converted into undirected nx.Graph objects. :param other: MoleculeGraph object to be compared. + Returns: bool """ diff --git a/pymatgen/analysis/interfaces/substrate_analyzer.py b/pymatgen/analysis/interfaces/substrate_analyzer.py index 78ccab9a443..48e51d0d069 100644 --- a/pymatgen/analysis/interfaces/substrate_analyzer.py +++ b/pymatgen/analysis/interfaces/substrate_analyzer.py @@ -93,6 +93,7 @@ class SubstrateAnalyzer(ZSLGenerator): def __init__(self, film_max_miller=1, substrate_max_miller=1, **kwargs): """ Initializes the substrate analyzer + Args: zslgen(ZSLGenerator): Defaults to a ZSLGenerator with standard tolerances, but can be fed one with custom tolerances diff --git a/pymatgen/analysis/interfaces/zsl.py b/pymatgen/analysis/interfaces/zsl.py index e7c7a0cfbe3..56d5e3b15df 100644 --- a/pymatgen/analysis/interfaces/zsl.py +++ b/pymatgen/analysis/interfaces/zsl.py @@ -92,6 +92,7 @@ def __init__( """ Initialize a Zur Super Lattice Generator for a specific film and substrate + Args: max_area_ratio_tol(float): Max tolerance on ratio of super-lattices to consider equal @@ -113,6 +114,7 @@ def generate_sl_transformation_sets(self, film_area, substrate_area): 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 + Args: film_area(int): the unit cell area for the film substrate_area(int): the unit cell area for the substrate diff --git a/pymatgen/analysis/local_env.py b/pymatgen/analysis/local_env.py index cd08427201a..adc110d32cb 100644 --- a/pymatgen/analysis/local_env.py +++ b/pymatgen/analysis/local_env.py @@ -606,7 +606,8 @@ def get_bonded_structure( will raise ValueError, while 'take_majority_drop' ignores this site altogether and 'take_max_species' will use Fe as the site specie. - Returns: a pymatgen.analysis.graphs.StructureGraph object + Returns: + StructureGraph: object from pymatgen.analysis.graphs """ structure = _handle_disorder(structure, on_disorder) @@ -1248,11 +1249,13 @@ def extend_structure_molecules(self): def get_max_bond_distance(self, el1_sym, el2_sym): """ Use Jmol algorithm to determine bond length from atomic parameters + Args: el1_sym: (str) symbol of atom 1 el2_sym: (str) symbol of atom 2. - Returns: (float) max bond length + Returns: + float: max bond length """ return sqrt((self.el_radius[el1_sym] + self.el_radius[el2_sym] + self.tol) ** 2) @@ -1503,7 +1506,8 @@ def get_bonded_structure(self, structure: Structure, decorate: bool = False) -> with order parameters using neighbors determined by this NearNeighbor class - Returns: a pymatgen.analysis.graphs.MoleculeGraph object + Returns: + MoleculeGraph: object from pymatgen.analysis.graphs """ if decorate: # Decorate all sites in the underlying structure @@ -1607,6 +1611,7 @@ def get_nn_info(self, structure: Structure, n: int): :param structure: input Molecule. :param n: index of site for which to determine near neighbors. + Returns: [dict] representing a neighboring site and the type of bond present between site n and the neighboring site. @@ -1636,8 +1641,7 @@ def get_nn_info(self, structure: Structure, n: int): def get_bonded_structure(self, structure: Structure, decorate: bool = False) -> MoleculeGraph: # type: ignore """ - Obtain a MoleculeGraph object using this NearNeighbor - class. + Obtain a MoleculeGraph object using this NearNeighbor class. Args: structure: Molecule object. @@ -1645,7 +1649,8 @@ def get_bonded_structure(self, structure: Structure, decorate: bool = False) -> with order parameters using neighbors determined by this NearNeighbor class - Returns: a pymatgen.analysis.graphs.MoleculeGraph object + Returns: + MoleculeGraph: object from pymatgen.analysis.graphs """ # requires optional dependency which is why it's not a top-level import from pymatgen.analysis.graphs import MoleculeGraph @@ -2024,7 +2029,8 @@ def get_neighbors_of_site_with_index(struct, n, approach="min_dist", delta=0.1, delta (float): tolerance involved in neighbor finding. cutoff (float): (large) radius to find tentative neighbors. - Returns: neighbor sites. + Returns: + neighbor sites. """ if approach == "min_dist": return MinimumDistanceNN(tol=delta, cutoff=cutoff).get_nn(struct, n) @@ -2052,18 +2058,19 @@ def site_is_of_motif_type(struct, n, approach="min_dist", delta=0.1, cutoff=10, Args: struct (Structure): input structure. n (int): index of site in Structure object for which motif type - is to be determined. + is to be determined. approach (str): type of neighbor-finding approach, where - "min_dist" will use the MinimumDistanceNN class, - "voronoi" the VoronoiNN class, "min_OKeeffe" the - MinimumOKeeffe class, and "min_VIRE" the MinimumVIRENN class. + "min_dist" will use the MinimumDistanceNN class, + "voronoi" the VoronoiNN class, "min_OKeeffe" the + MinimumOKeeffe class, and "min_VIRE" the MinimumVIRENN class. delta (float): tolerance involved in neighbor finding. cutoff (float): (large) radius to find tentative neighbors. thresh (dict): thresholds for motif criteria (currently, required - keys and their default values are "qtet": 0.5, - "qoct": 0.5, "qbcc": 0.5, "q6": 0.4). + keys and their default values are "qtet": 0.5, + "qoct": 0.5, "qbcc": 0.5, "q6": 0.4). - Returns: motif type (str). + Returns: + str: motif type """ if thresh is None: thresh = {"qtet": 0.5, "qoct": 0.5, "qbcc": 0.5, "q6": 0.4, "qtribipyr": 0.8, "qsqpyr": 0.8} @@ -4062,6 +4069,7 @@ def _semicircle_integral(dist_bins, idx): def transform_to_length(nn_data, length): """ Given NNData, transforms data to the specified fingerprint length + Args: nn_data: (NNData) length: (int) desired length of NNData. @@ -4198,11 +4206,11 @@ def extend_structure_molecules(self): @classmethod def from_preset(cls, preset): """ - Initialize a CutOffDictNN according to a preset set of cut-offs. + Initialize a CutOffDictNN according to a preset set of cutoffs. Args: preset (str): A preset name. The list of supported presets are: - - "vesta_2019": The distance cut-offs used by the VESTA + - "vesta_2019": The distance cutoffs used by the VESTA visualisation program. Returns: diff --git a/pymatgen/analysis/magnetism/analyzer.py b/pymatgen/analysis/magnetism/analyzer.py index 6436c9cd116..cb00b523b3e 100644 --- a/pymatgen/analysis/magnetism/analyzer.py +++ b/pymatgen/analysis/magnetism/analyzer.py @@ -347,7 +347,8 @@ def get_structure_with_only_magnetic_atoms(self, make_primitive: bool = True) -> make_primitive: Whether to make structure primitive after removing non-magnetic atoms (Default value = True) - Returns: Structure + Returns: + Structure """ sites = [site for site in self.structure if abs(site.properties["magmom"]) > 0] @@ -407,13 +408,12 @@ def magmoms(self) -> np.ndarray: return np.array(self.structure.site_properties["magmom"]) @property - def types_of_magnetic_species( - self, - ) -> tuple[Element | Species | DummySpecies, ...]: + def types_of_magnetic_species(self) -> tuple[Element | Species | DummySpecies, ...]: """Equivalent to Structure.types_of_specie but only returns magnetic species. - Returns: types of Species as a list + Returns: + tuple: types of Species """ if self.number_of_magnetic_sites > 0: structure = self.get_structure_with_only_magnetic_atoms() @@ -421,9 +421,7 @@ def types_of_magnetic_species( return () @property - def types_of_magnetic_specie( - self, - ) -> tuple[Element | Species | DummySpecies, ...]: + def types_of_magnetic_specie(self) -> tuple[Element | Species | DummySpecies, ...]: """Specie->Species rename. Used to maintain backwards compatibility.""" return self.types_of_magnetic_species @@ -433,23 +431,24 @@ def magnetic_species_and_magmoms(self) -> dict[str, Any]: their associated magmoms. Will return a list if there are multiple magmoms per species. - Returns: dict of magnetic species and magmoms + Returns: + dict of magnetic species and magmoms """ structure = self.get_ferromagnetic_structure() - magtypes: dict = {str(site.specie): set() for site in structure if site.properties["magmom"] != 0} + mag_types: dict = {str(site.specie): set() for site in structure if site.properties["magmom"] != 0} for site in structure: if site.properties["magmom"] != 0: - magtypes[str(site.specie)].add(site.properties["magmom"]) + mag_types[str(site.specie)].add(site.properties["magmom"]) - for sp, magmoms in magtypes.items(): + for sp, magmoms in mag_types.items(): if len(magmoms) == 1: - magtypes[sp] = magmoms.pop() + mag_types[sp] = magmoms.pop() else: - magtypes[sp] = sorted(magmoms) + mag_types[sp] = sorted(magmoms) - return magtypes + return mag_types @property def number_of_magnetic_sites(self) -> int: @@ -484,8 +483,8 @@ def ordering(self) -> Ordering: """Applies heuristics to return a magnetic ordering for a collinear magnetic structure. Result is not guaranteed for correctness. - Returns: Ordering Enum ('FiM' is used as the abbreviation for - ferrimagnetic) + Returns: + Ordering: Enum ('FiM' is used as the abbreviation for ferrimagnetic) """ if not self.is_collinear: warnings.warn("Detecting ordering in non-collinear structures not yet implemented.") @@ -934,7 +933,8 @@ def _generate_ordered_structures( ) -> tuple[list[Structure], list[str]]: """Apply our input structure to our list of transformations and output a list of ordered structures that have been pruned for duplicates and for those - with low symmetry (optional). + with low symmetry (optional). Sets self.ordered_structures + and self.ordered_structures_origins instance variables. Args: sanitized_input_structure: A sanitized input structure @@ -943,10 +943,9 @@ def _generate_ordered_structures( enumeration strategy (key), the enumeration strategy name is just for record keeping - Returns: None (sets self.ordered_structures - and self.ordered_structures_origins instance variables) - Returns: List of Structures + Returns: + list[Structures] """ ordered_structures = self.ordered_structures ordered_structures_origins = self.ordered_structure_origins @@ -1072,10 +1071,11 @@ def magnetic_deformation(structure_A: Structure, structure_B: Structure) -> Magn doi: 10.1021/acs.chemmater.6b04729 Args: - structure_A: Structure - structure_B: Structure + structure_A: Structure + structure_B: Structure - Returns: Magnetic deformation + Returns: + MagneticDeformation """ # retrieve orderings of both input structures ordering_a = CollinearMagneticStructureAnalyzer(structure_A, overwrite_magmom_mode="none").ordering diff --git a/pymatgen/analysis/magnetism/jahnteller.py b/pymatgen/analysis/magnetism/jahnteller.py index 73fe137a011..4987a9c9b0c 100644 --- a/pymatgen/analysis/magnetism/jahnteller.py +++ b/pymatgen/analysis/magnetism/jahnteller.py @@ -338,7 +338,8 @@ def _get_number_of_d_electrons(species: Species) -> float: Args: species: Species object - Returns: Number of d electrons. + Returns: + int: Number of d electrons. """ # TODO: replace with more generic Hund's rule algorithm? @@ -346,11 +347,11 @@ def _get_number_of_d_electrons(species: Species) -> float: elec = species.full_electronic_structure if len(elec) < 4 or elec[-1][1] != "s" or elec[-2][1] != "d": raise AttributeError(f"Invalid element {species.symbol} for crystal field calculation.") - nelectrons = int(elec[-1][2] + elec[-2][2] - species.oxi_state) - if nelectrons < 0 or nelectrons > 10: + n_electrons = int(elec[-1][2] + elec[-2][2] - species.oxi_state) + if n_electrons < 0 or n_electrons > 10: raise AttributeError(f"Invalid oxidation state {species.oxi_state} for element {species.symbol}") - return nelectrons + return n_electrons def get_magnitude_of_effect_from_species(self, species: str | Species, spin_state: str, motif: str) -> str: """ diff --git a/pymatgen/analysis/phase_diagram.py b/pymatgen/analysis/phase_diagram.py index 380857b724b..bd804fb130d 100644 --- a/pymatgen/analysis/phase_diagram.py +++ b/pymatgen/analysis/phase_diagram.py @@ -51,7 +51,7 @@ class PDEntry(Entry): Attributes: composition (Composition): The composition associated with the PDEntry. energy (float): The energy associated with the entry. - name (str): A name for the entry. This is the string shown in the phase diagrams. + name (str): A name for the entry. This is the string shown in the phase diagrams. By default, this is the reduced formula for the composition, but can be set to some other string for display purposes. attribute (MSONable): A arbitrary attribute. Can be used to specify that the @@ -2978,8 +2978,7 @@ def _create_plotly_markers(self, highlight_entries=None, label_uncertainties=Fal """ def get_marker_props(coords, entries): - """ - Method for getting marker locations, hovertext, and error bars + """Method for getting marker locations, hovertext, and error bars from pd_plot_data. """ x, y, z, texts, energies, uncertainties = [], [], [], [], [], [] diff --git a/pymatgen/analysis/pourbaix_diagram.py b/pymatgen/analysis/pourbaix_diagram.py index 3b8e9692f9d..62bfe18532c 100644 --- a/pymatgen/analysis/pourbaix_diagram.py +++ b/pymatgen/analysis/pourbaix_diagram.py @@ -525,7 +525,7 @@ def _convert_entries_to_points(self, pourbaix_entries): vecs *= norms return vecs - def _get_hull_in_nph_nphi_space(self, entries): + def _get_hull_in_nph_nphi_space(self, entries) -> tuple[list[PourbaixEntry], list[Simplex]]: """ Generates convex hull of Pourbaix diagram entries in composition, npH, and nphi space. This enables filtering of multi-entries @@ -536,8 +536,9 @@ def _get_hull_in_nph_nphi_space(self, entries): entries ([PourbaixEntry]): list of PourbaixEntries to construct the convex hull - Returns: list of entries and stable facets corresponding to that - list of entries + Returns: + tuple[list[PourbaixEntry], list[Simplex]]: PourbaixEntry list and stable + facets corresponding to that list """ ion_entries = [entry for entry in entries if entry.phase_type == "Ion"] solid_entries = [entry for entry in entries if entry.phase_type == "Solid"] @@ -802,6 +803,7 @@ def get_pourbaix_domains(pourbaix_entries, limits=None): def find_stable_entry(self, pH, V): """ Finds stable entry at a pH,V condition + Args: pH (float): pH to find stable entry V (float): V to find stable entry. diff --git a/pymatgen/analysis/solar/slme.py b/pymatgen/analysis/solar/slme.py index 363c351960e..25618bd4906 100644 --- a/pymatgen/analysis/solar/slme.py +++ b/pymatgen/analysis/solar/slme.py @@ -75,7 +75,7 @@ def parse_dielectric_data(data): a list of ``[xx, yy, zz, xy , xz, yz ]`` dielectric tensor elements. Returns: - (np.array): a Nx3 numpy array. Each row contains the eigenvalues + np.array: a Nx3 numpy array. Each row contains the eigenvalues for the corresponding row in `data`. """ return np.array([np.linalg.eig(to_matrix(*e))[0] for e in data]) diff --git a/pymatgen/analysis/structure_analyzer.py b/pymatgen/analysis/structure_analyzer.py index 1300dd0125b..0ed762d18ad 100644 --- a/pymatgen/analysis/structure_analyzer.py +++ b/pymatgen/analysis/structure_analyzer.py @@ -378,8 +378,8 @@ def get_max_bond_lengths(structure, el_radius_updates=None): structure: (structure) el_radius_updates: (dict) symbol->float to update atom_ic radii - Returns: (dict) - (Element1, Element2) -> float. The two elements are - ordered by Z. + Returns: + dict[(Element1, Element2)], float]: The two elements are ordered by Z. """ # jmc = JMolCoordFinder(el_radius_updates) jmnn = JmolNN(el_radius_updates=el_radius_updates) diff --git a/pymatgen/analysis/structure_matcher.py b/pymatgen/analysis/structure_matcher.py index 52abbeaa944..4bca233ed6a 100644 --- a/pymatgen/analysis/structure_matcher.py +++ b/pymatgen/analysis/structure_matcher.py @@ -270,6 +270,7 @@ def are_equal(self, sp1, sp2) -> bool: def get_hash(self, composition): """ :param composition: Composition. + Returns: 1. Difficult to define sensible hash """ diff --git a/pymatgen/analysis/surface_analysis.py b/pymatgen/analysis/surface_analysis.py index dc27d0a55e4..636b26abd17 100644 --- a/pymatgen/analysis/surface_analysis.py +++ b/pymatgen/analysis/surface_analysis.py @@ -149,8 +149,8 @@ def as_dict(self): def gibbs_binding_energy(self, eads=False): """ - Returns the adsorption energy or Gibbs binding energy - of an adsorbate on a surface + Returns the adsorption energy or Gibbs binding energy of an adsorbate on a surface. + Args: eads (bool): Whether to calculate the adsorption energy (True) or the binding energy (False) which is just @@ -1199,21 +1199,20 @@ def surface_chempot_range_map( ) # Save the chempot range for dmu1 and dmu2 - for entry, v in range_dict.items(): - if not v: + for entry, vertex in range_dict.items(): + if not vertex: continue - if entry not in vertices_dict: - vertices_dict[entry] = [] + vertices_dict.setdefault(entry, []) selist = se_dict[entry] - vertices_dict[entry].append({delu1: dmu1, delu2: [v, selist]}) + vertices_dict[entry].append({delu1: dmu1, delu2: [vertex, selist]}) # Plot the edges of the phases - for entry, v in vertices_dict.items(): + for entry, vertex in vertices_dict.items(): xvals, yvals = [], [] # Plot each edge of a phase within the borders - for ii, pt1 in enumerate(v): + for ii, pt1 in enumerate(vertex): # Determine if the surface energy at this lower range # of dmu2 is negative. If so, shade this region. if len(pt1[delu2][1]) == 3: @@ -1228,9 +1227,9 @@ def surface_chempot_range_map( # in se<0, shade the entire y range ax.plot([pt1[delu1], pt1[delu1]], range2, "k--") - if ii == len(v) - 1: + if ii == len(vertex) - 1: break - pt2 = v[ii + 1] + pt2 = vertex[ii + 1] if not show_unphyiscal_only: ax.plot( [pt1[delu1], pt2[delu1]], @@ -1243,7 +1242,7 @@ def surface_chempot_range_map( yvals.extend([pt1[delu2][0][0], pt2[delu2][0][0]]) # Plot the edge along the max x value - pt = v[-1] + pt = vertex[-1] delu1, delu2 = pt xvals.extend([pt[delu1], pt[delu1]]) yvals.extend(pt[delu2][0]) @@ -1463,6 +1462,7 @@ def get_locpot_along_slab_plot(self, label_energies=True, plt=None, label_fontsi def get_labels(self, plt, label_fontsize=10): """ Handles the optional labelling of the plot with relevant quantities + Args: plt (plt): Plot of the locpot vs c axis label_fontsize (float): Fontsize of labels diff --git a/pymatgen/analysis/transition_state.py b/pymatgen/analysis/transition_state.py index 310d61ee4fc..e863474832b 100644 --- a/pymatgen/analysis/transition_state.py +++ b/pymatgen/analysis/transition_state.py @@ -84,7 +84,7 @@ def setup_spline(self, spline_options=None): def from_outcars(cls, outcars, structures, **kwargs): """ Initializes an NEBAnalysis from Outcar and Structure objects. Use - the static constructors, e.g., :class:`from_dir` instead if you + the static constructors, e.g., from_dir instead if you prefer to have these automatically generated from a directory of NEB calculations. diff --git a/pymatgen/analysis/wulff.py b/pymatgen/analysis/wulff.py index b6bfaaca3a6..8ceceba56d9 100644 --- a/pymatgen/analysis/wulff.py +++ b/pymatgen/analysis/wulff.py @@ -21,6 +21,8 @@ import warnings from typing import TYPE_CHECKING +import matplotlib as mpl +import matplotlib.pyplot as plt import numpy as np import plotly.graph_objs as go from scipy.spatial import ConvexHull @@ -267,8 +269,6 @@ def _get_colors(self, color_set, alpha, off_color, custom_colors=None): tuple: color_list, color_proxy, color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff_list """ - import matplotlib as mpl - import matplotlib.pyplot as plt color_list = [off_color] * len(self.hkl_list) color_proxy_on_wulff = [] @@ -380,8 +380,6 @@ def get_plot( Return: (matplotlib.pyplot) """ - import matplotlib as mpl - import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D, art3d colors = self._get_colors(color_set, alpha, off_color, custom_colors=custom_colors or {}) diff --git a/pymatgen/analysis/xps.py b/pymatgen/analysis/xps.py index c0bb14ed5e9..e3aed0853cb 100644 --- a/pymatgen/analysis/xps.py +++ b/pymatgen/analysis/xps.py @@ -80,6 +80,7 @@ def from_dos(cls, dos: CompleteDos): """ :param dos: CompleteDos object with project element-orbital DOS. Can be obtained from Vasprun.get_complete_dos. :param sigma: Smearing for Gaussian. + Returns: XPS """ diff --git a/pymatgen/apps/borg/hive.py b/pymatgen/apps/borg/hive.py index 3845ff20bff..c8f7255d534 100644 --- a/pymatgen/apps/borg/hive.py +++ b/pymatgen/apps/borg/hive.py @@ -83,7 +83,7 @@ def __init__(self, inc_structure=False, parameters=None, data=None): ComputedEntries. parameters (list): Input parameters to include. It has to be one of the properties supported by the Vasprun object. See - :class:`pymatgen.io.vasp.Vasprun`. If parameters is None, + pymatgen.io.vasp.Vasprun. If parameters is None, a default set of parameters that are necessary for typical post-processing will be set. data (list): Output data to include. Has to be one of the properties @@ -312,7 +312,7 @@ def __init__(self, inc_structure=False, parameters=None, data=None, file_extensi ComputedEntries. parameters (list): Input parameters to include. It has to be one of the properties supported by the GaussianOutput object. See - :class:`pymatgen.io.gaussianio GaussianOutput`. The parameters + pymatgen.io.gaussianio GaussianOutput. The parameters have to be one of python's primitive types, i.e., list, dict of strings and integers. If parameters is None, a default set of parameters will be set. diff --git a/pymatgen/apps/borg/queen.py b/pymatgen/apps/borg/queen.py index 06a243e5c84..cfad47a3b7a 100644 --- a/pymatgen/apps/borg/queen.py +++ b/pymatgen/apps/borg/queen.py @@ -26,7 +26,7 @@ def __init__(self, drone, rootpath=None, number_of_drones=1): """ Args: drone (Drone): An implementation of - :class:`pymatgen.apps.borg.hive.AbstractDrone` to use for + pymatgen.apps.borg.hive.AbstractDrone to use for assimilation. rootpath (str): The root directory to start assimilation. Leave it as None if you want to do assimilation later, or is using the diff --git a/pymatgen/command_line/critic2_caller.py b/pymatgen/command_line/critic2_caller.py index 4d74c01f7e5..58bc0e1cf52 100644 --- a/pymatgen/command_line/critic2_caller.py +++ b/pymatgen/command_line/critic2_caller.py @@ -394,11 +394,11 @@ def laplacian(self): @property def ellipticity(self): - """Most meaningful for bond critical points, - can be physically interpreted as e.g. degree - of pi-bonding in organic molecules. Consult - literature for more information. - Returns: The ellpiticity of the field at the critical point. + """Most meaningful for bond critical points, can be physically interpreted as e.g. + degree of pi-bonding in organic molecules. Consult literature for more info. + + Returns: + float: The ellipticity of the field at the critical point. """ eig, _ = np.linalg.eig(self.field_hessian) eig.sort() @@ -468,8 +468,7 @@ class with bonding information. By default, this returns self._remap_indices() def structure_graph(self, include_critical_points=("bond", "ring", "cage")): - """A StructureGraph object describing bonding information - in the crystal. + """A StructureGraph object describing bonding information in the crystal. Args: include_critical_points: add DummySpecies for @@ -477,7 +476,8 @@ def structure_graph(self, include_critical_points=("bond", "ring", "cage")): "nucleus", "bond", "ring", "cage", set to None to disable - Returns: a StructureGraph + Returns: + StructureGraph """ structure = self.structure.copy() @@ -589,22 +589,23 @@ def get_critical_point_for_site(self, n: int): Args: n (int): Site index. - Returns: A CriticalPoint instance + Returns: + CriticalPoint """ return self.critical_points[self.nodes[n]["unique_idx"]] - def get_volume_and_charge_for_site(self, n): + def get_volume_and_charge_for_site(self, idx): """ Args: - n: Site index n. + idx: Site index. - Returns: A dict containing "volume" and "charge" keys, - or None if YT integration not performed + Returns: + dict: with "volume" and "charge" keys, or None if YT integration not performed """ # pylint: disable=E1101 if not self._node_values: return None - return self._node_values[n] + return self._node_values[idx] def _parse_cpreport(self, cpreport): def get_type(signature: int, is_nucleus: bool): @@ -874,7 +875,7 @@ def _add_edge(self, idx, from_idx, from_lvec, to_idx, to_lvec): :param from_lvec: vector of lattice image the from node is in as tuple of ints :param to_idx: to index of node - :param to_lvec: vector of lattice image the to node is in as + :param to_lvec: vector of lattice image the to node is in as tuple of ints """ self.edges[idx] = { diff --git a/pymatgen/command_line/gulp_caller.py b/pymatgen/command_line/gulp_caller.py index 791992eb35a..6117405acc2 100644 --- a/pymatgen/command_line/gulp_caller.py +++ b/pymatgen/command_line/gulp_caller.py @@ -625,7 +625,7 @@ def get_relaxed_structure(gout: str): class GulpCaller: - """Class to run gulp from commandline.""" + """Class to run gulp from command line.""" def __init__(self, cmd="gulp"): """Initialize with the executable if not in the standard path. diff --git a/pymatgen/core/bonds.py b/pymatgen/core/bonds.py index 386fe36fde6..fc37568e77b 100644 --- a/pymatgen/core/bonds.py +++ b/pymatgen/core/bonds.py @@ -49,7 +49,8 @@ def length(self) -> float: return self.site1.distance(self.site2) def get_bond_order(self, tol: float = 0.2, default_bl: float | None = None) -> float: - """The bond order according the distance between the two sites + """The bond order according the distance between the two sites. + Args: tol (float): Relative tolerance to test. (1 + tol) * the longest bond distance is considered diff --git a/pymatgen/core/interface.py b/pymatgen/core/interface.py index ab1c2b97d30..ef035e77640 100644 --- a/pymatgen/core/interface.py +++ b/pymatgen/core/interface.py @@ -41,7 +41,7 @@ def __init__( Args: lattice (Lattice/3x3 array): The lattice, either as a - :class:`pymatgen.core.lattice.Lattice` or + 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 lattice with lattice vectors [10,0,0], [20,10,0] and [0,0,30]. diff --git a/pymatgen/core/ion.py b/pymatgen/core/ion.py index ca7a449c947..025a2702e08 100644 --- a/pymatgen/core/ion.py +++ b/pymatgen/core/ion.py @@ -35,6 +35,7 @@ def from_formula(cls, formula: str) -> Ion: Also note that (aq) can be included in the formula, e.g. "NaOH (aq)". :param formula: + Returns: Ion """ diff --git a/pymatgen/core/lattice.py b/pymatgen/core/lattice.py index 2f9ec14da23..c84113641fd 100644 --- a/pymatgen/core/lattice.py +++ b/pymatgen/core/lattice.py @@ -1656,7 +1656,8 @@ def get_miller_index_from_coords( def get_recp_symmetry_operation(self, symprec: float = 0.01) -> list: """Find the symmetric operations of the reciprocal lattice, - to be used for hkl transformations + to be used for hkl transformations. + Args: symprec: default is 0.001. """ @@ -1865,8 +1866,8 @@ def _compute_cube_index(coords: np.ndarray, global_min: float, radius: float) -> global_min: (float) lower boundary of coordinates radius: (float) cutoff radius. - Returns: (nx3 array) int indices - + Returns: + np.ndarray: nx3 array int indices """ return np.array(np.floor((coords - global_min) / radius), dtype=int) @@ -1879,8 +1880,8 @@ def _one_to_three(label1d: np.ndarray, ny: int, nz: int) -> np.ndarray: ny: (int) number of cells in y direction nz: (int) number of cells in z direction - Returns: (nx3) int array of index - + Returns: + np.ndarray: nx3 array int indices """ last = np.mod(label1d, nz) second = np.mod((label1d - last) / nz, ny) diff --git a/pymatgen/core/spectrum.py b/pymatgen/core/spectrum.py index 00208317d68..292dac6dafb 100644 --- a/pymatgen/core/spectrum.py +++ b/pymatgen/core/spectrum.py @@ -122,7 +122,7 @@ def get_interpolated_value(self, x: float) -> list[float]: """Returns an interpolated y value for a particular x value. Args: - x: x value to return the y value for + x: x value to return the y value for Returns: Value of y at x @@ -181,7 +181,8 @@ def __mul__(self, other): __rmul__ = __mul__ def __truediv__(self, other): - """True division of y + """True division of y. + Args: other: The divisor. @@ -191,7 +192,8 @@ def __truediv__(self, other): return self.__class__(self.x, self.y.__truediv__(other), *self._args, **self._kwargs) def __floordiv__(self, other): - """True division of y + """True division of y. + Args: other: The divisor. diff --git a/pymatgen/core/structure.py b/pymatgen/core/structure.py index d7fa6e33777..237199f91e6 100644 --- a/pymatgen/core/structure.py +++ b/pymatgen/core/structure.py @@ -94,23 +94,20 @@ def __getitem__(self, idx: int): return (self, self.nn_distance, self.index)[idx] def as_dict(self) -> dict: # type: ignore - """Note that method calls the super of Site, which is MSONable itself. - - Returns: dict - """ + """Note that method calls the super of Site, which is MSONable itself.""" return super(Site, self).as_dict() # pylint: disable=E1003 @classmethod - def from_dict(cls, d: dict) -> Neighbor: # type: ignore + def from_dict(cls, dct: dict) -> Neighbor: # type: ignore """Returns a Neighbor from a dict. Args: - d: MSONable dict format. + dct: MSONable dict format. Returns: Neighbor """ - return super(Site, cls).from_dict(d) # pylint: disable=E1003 + return super(Site, cls).from_dict(dct) # pylint: disable=E1003 class PeriodicNeighbor(PeriodicSite): @@ -169,10 +166,7 @@ def __getitem__(self, idx: int | slice): return (self, self.nn_distance, self.index, self.image)[idx] def as_dict(self) -> dict: # type: ignore - """Note that method calls the super of Site, which is MSONable itself. - - Returns: dict - """ + """Note that method calls the super of Site, which is MSONable itself.""" return super(Site, self).as_dict() # pylint: disable=E1003 @classmethod @@ -856,7 +850,7 @@ def __init__( Args: lattice (Lattice/3x3 array): The lattice, either as a - :class:`pymatgen.core.lattice.Lattice` or + 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 lattice with lattice vectors [10,0,0], [20,10,0] and [0,0,30]. @@ -1002,7 +996,7 @@ def from_spacegroup( 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 - :class:`pymatgen.core.lattice.Lattice` or + 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 lattice with lattice vectors [10,0,0], [20,10,0] and [0,0,30]. @@ -1091,14 +1085,14 @@ def from_magnetic_spacegroup( All equivalent sites are generated from the spacegroup operations. Args: - msg (str/list/:class:`pymatgen.symmetry.maggroups.MagneticSpaceGroup`): + 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". 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 - :class:`pymatgen.core.lattice.Lattice` or + 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 lattice with lattice vectors [10,0,0], [20,10,0] and [0,0,30]. @@ -1252,7 +1246,7 @@ def matches(self, other: IStructure | Structure, anonymous: bool = False, **kwar anonymous (bool): Whether to use anonymous structure matching which allows distinct species in one structure to map to another. **kwargs: Same **kwargs as in - :class:`pymatgen.analysis.structure_matcher.StructureMatcher`. + pymatgen.analysis.structure_matcher.StructureMatcher. Returns: bool: True if the structures are similar under some affine transformation. @@ -1491,7 +1485,8 @@ def _get_neighbor_list_py( exclude_self (bool): whether to exclude atom neighboring with itself within numerical tolerance distance, default to True - Returns: (center_indices, points_indices, offset_vectors, distances) + Returns: + tuple: (center_indices, points_indices, offset_vectors, distances) """ neighbors = self.get_all_neighbors_py( r=r, include_index=True, include_image=True, sites=sites, numerical_tol=1e-8 @@ -1542,7 +1537,8 @@ def get_neighbor_list( exclude_self (bool): whether to exclude atom neighboring with itself within numerical tolerance distance, default to True - Returns: (center_indices, points_indices, offset_vectors, distances) + Returns: + tuple: (center_indices, points_indices, offset_vectors, distances) """ try: from pymatgen.optimization.neighbors import find_points_in_spheres @@ -1608,8 +1604,9 @@ def get_symmetric_neighbor_list( exclude_self (bool): whether to exclude atom neighboring with itself within numerical tolerance distance, default to True - Returns: (center_indices, points_indices, offset_vectors, distances, - symmetry_indices, symmetry_ops) + Returns: + tuple: (center_indices, points_indices, offset_vectors, distances, + symmetry_indices, symmetry_ops) """ from pymatgen.symmetry.groups import SpaceGroup @@ -1764,7 +1761,7 @@ def get_all_neighbors( ok in most instances. Returns: - [[:class:`pymatgen.core.structure.PeriodicNeighbor`], ..] + [[pymatgen.core.structure.PeriodicNeighbor], ..] """ if sites is None: sites = self.sites @@ -2857,8 +2854,7 @@ def from_file(cls, filename, primitive=False, sort=False, merge_tol=0.0, **kwarg class IMolecule(SiteCollection, MSONable): """Basic immutable Molecule object without periodicity. Essentially a sequence of sites. IMolecule is made to be immutable so that they can - function as keys in a dict. For a mutable molecule, - use the :class:Molecule. + function as keys in a dict. For a mutable object, use the Molecule class. Molecule extends Sequence and Hashable, which means that in many cases, it can be used like any Python sequence. Iterating through a molecule is @@ -3539,7 +3535,7 @@ def __init__( """Create a periodic structure. Args: - lattice: The lattice, either as a pymatgen.core.lattice.Lattice or + 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 lattice with lattice vectors [10,0,0], [20,10,0] and [0,0,30]. diff --git a/pymatgen/core/surface.py b/pymatgen/core/surface.py index abce1dac2fc..738b809b540 100644 --- a/pymatgen/core/surface.py +++ b/pymatgen/core/surface.py @@ -21,7 +21,7 @@ import warnings from functools import reduce from math import gcd -from typing import Literal +from typing import TYPE_CHECKING import numpy as np from monty.fractions import lcm @@ -37,6 +37,9 @@ from pymatgen.util.coord import in_coord_list from pymatgen.util.due import Doi, due +if TYPE_CHECKING: + from pymatgen.symmetry.groups import CrystalSystem + __author__ = "Richard Tran, Wenhao Sun, Zihan Xu, Shyue Ping Ong" due.dcite( @@ -93,7 +96,7 @@ def __init__( Args: lattice (Lattice/3x3 array): The lattice, either as a - :class:`pymatgen.core.lattice.Lattice` or + 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 lattice with lattice vectors [10,0,0], [20,10,0] and [0,0,30]. @@ -1520,8 +1523,7 @@ def get_symmetrically_equivalent_miller_indices( structure, miller_index, return_hkil=True, - system: Literal["triclinic", "monoclinic", "orthorhombic", "tetragonal", "trigonal", "hexagonal", "cubic"] - | None = None, + system: CrystalSystem | None = None, ): """Returns all symmetrically equivalent indices for a given structure. Analysis is based on the symmetry of the reciprocal lattice of the structure. @@ -1538,8 +1540,8 @@ def get_symmetrically_equivalent_miller_indices( # Change to hkl if hkil because in_coord_list only handles tuples of 3 miller_index = (miller_index[0], miller_index[1], miller_index[3]) if len(miller_index) == 4 else miller_index mmi = max(np.abs(miller_index)) - r = list(range(-mmi, mmi + 1)) - r.reverse() + rng = list(range(-mmi, mmi + 1)) + rng.reverse() sg = None if not system: @@ -1556,7 +1558,7 @@ def get_symmetrically_equivalent_miller_indices( symm_ops = structure.lattice.get_recp_symmetry_operation() equivalent_millers = [miller_index] - for miller in itertools.product(r, r, r): + for miller in itertools.product(rng, rng, rng): if miller == miller_index: continue if any(i != 0 for i in miller): diff --git a/pymatgen/electronic_structure/bandstructure.py b/pymatgen/electronic_structure/bandstructure.py index 00c3572c4c7..dfbb0f0ca09 100644 --- a/pymatgen/electronic_structure/bandstructure.py +++ b/pymatgen/electronic_structure/bandstructure.py @@ -44,7 +44,7 @@ def __init__( """ Args: coords: coordinate of the kpoint as a numpy array - lattice: A pymatgen.core.lattice.Lattice object representing + lattice: A pymatgen.core.Lattice object representing the reciprocal lattice of the kpoint to_unit_cell: Translates fractional coordinate to the basic unit cell, i.e., all fractional coordinates satisfy 0 <= a < 1. @@ -66,7 +66,7 @@ def __init__( @property def lattice(self): """The lattice associated with the kpoint. It's a - pymatgen.core.lattice.Lattice object. + pymatgen.core.Lattice object. """ return self._lattice @@ -525,7 +525,8 @@ def get_sym_eq_kpoints(self, kpoint, cartesian=False, tol: float = 1e-2): return np.delete(points, rm_list, axis=0) def get_kpoint_degeneracy(self, kpoint, cartesian=False, tol: float = 1e-2): - """Returns degeneracy of a given k-point based on structure symmetry + """Returns degeneracy of a given k-point based on structure symmetry. + Args: kpoint (1x3 array): coordinate of the k-point cartesian (bool): kpoint is in Cartesian or fractional coordinates diff --git a/pymatgen/electronic_structure/boltztrap.py b/pymatgen/electronic_structure/boltztrap.py index eb157181f7f..e3a3ccb79b2 100644 --- a/pymatgen/electronic_structure/boltztrap.py +++ b/pymatgen/electronic_structure/boltztrap.py @@ -1682,7 +1682,8 @@ 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 + """Parses .transdos (total DOS) and .transdos_x_y (partial DOS) files. + Args: path_dir: (str) dir containing DOS files efermi: (float) Fermi energy @@ -1793,7 +1794,8 @@ def parse_struct(path_dir): @staticmethod def parse_cond_and_hall(path_dir, doping_levels=None): - """Parses the conductivity and Hall tensors + """Parses the conductivity and Hall tensors. + Args: path_dir: Path containing .condtens / .halltens files doping_levels: ([float]) - doping lvls, parse outtrans to get this. @@ -2260,8 +2262,8 @@ def seebeck_spb(eta, Lambda=0.5): def eta_from_seebeck(seeb, Lambda): """It takes a value of seebeck and adjusts the analytic seebeck until it's equal. - Returns: eta where the two seebeck coefficients are equal - (reduced chemical potential). + Returns: + float: eta where the two seebeck coefficients are equal (reduced chemical potential). """ from scipy.optimize import fsolve diff --git a/pymatgen/electronic_structure/cohp.py b/pymatgen/electronic_structure/cohp.py index 3ccaf61b7d8..c8da7ccb5b6 100644 --- a/pymatgen/electronic_structure/cohp.py +++ b/pymatgen/electronic_structure/cohp.py @@ -1036,6 +1036,7 @@ def get_icohp_by_label(self, label, summed_spin_channels=True, spin=Spin.up, orb summed_spin_channels: Boolean to indicate whether the ICOHPs/ICOOPs of both spin channels should be summed spin: if summed_spin_channels is equal to False, this spin indicates which spin channel should be returned orbitals: List of Orbital or "str(Orbital1)-str(Orbital2)" + Returns: float describing ICOHP/ICOOP value """ @@ -1080,19 +1081,20 @@ def get_summed_icohp_by_label_list(self, label_list, divisor=1.0, summed_spin_ch return sum_icohp / divisor def get_icohp_dict_by_bondlengths(self, minbondlength=0.0, maxbondlength=8.0): - """Get a dict of IcohpValues corresponding to certain bond lengths + """Get a dict of IcohpValues corresponding to certain bond lengths. + Args: minbondlength: defines the minimum of the bond lengths of the bonds maxbondlength: defines the maximum of the bond lengths of the bonds. Returns: - dict of IcohpValues, the keys correspond to the values from the initial list_labels. + dict of IcohpValues, the keys correspond to the values from the initial list_labels. """ - newicohp_dict = {} + new_icohp_dict = {} for value in self._icohplist.values(): if value._length >= minbondlength and value._length <= maxbondlength: - newicohp_dict[value._label] = value - return newicohp_dict + new_icohp_dict[value._label] = value + return new_icohp_dict def get_icohp_dict_of_site( self, @@ -1118,7 +1120,7 @@ def get_icohp_dict_of_site( Returns: dict of IcohpValues, the keys correspond to the values from the initial list_labels """ - newicohp_dict = {} + new_icohp_dict = {} for key, value in self._icohplist.items(): atomnumber1 = int(re.split(r"(\d+)", value._atom1)[1]) - 1 atomnumber2 = int(re.split(r"(\d+)", value._atom2)[1]) - 1 @@ -1135,19 +1137,20 @@ def get_icohp_dict_of_site( if value.summed_icohp >= minsummedicohp: if maxsummedicohp is not None: if value.summed_icohp <= maxsummedicohp: - newicohp_dict[key] = value + new_icohp_dict[key] = value else: - newicohp_dict[key] = value + new_icohp_dict[key] = value elif maxsummedicohp is not None: if value.summed_icohp <= maxsummedicohp: - newicohp_dict[key] = value + new_icohp_dict[key] = value else: - newicohp_dict[key] = value + new_icohp_dict[key] = value - return newicohp_dict + return new_icohp_dict def extremum_icohpvalue(self, summed_spin_channels=True, spin=Spin.up): - """Get ICOHP/ICOOP of strongest bond + """Get ICOHP/ICOOP of strongest bond. + Args: summed_spin_channels: Boolean to indicate whether the ICOHPs/ICOOPs of both spin channels should be summed. diff --git a/pymatgen/electronic_structure/plotter.py b/pymatgen/electronic_structure/plotter.py index 21dc76e79b9..c5e7e66eacb 100644 --- a/pymatgen/electronic_structure/plotter.py +++ b/pymatgen/electronic_structure/plotter.py @@ -22,7 +22,7 @@ from pymatgen.electronic_structure.bandstructure import BandStructureSymmLine from pymatgen.electronic_structure.boltztrap import BoltztrapError from pymatgen.electronic_structure.core import OrbitalType, Spin -from pymatgen.util.plotting import add_fig_kwargs, get_ax3d_fig_plt, pretty_plot +from pymatgen.util.plotting import add_fig_kwargs, get_ax3d_fig, pretty_plot try: from mayavi import mlab @@ -873,23 +873,24 @@ def plot_compare(self, other_plotter, legend=True) -> plt.Axes: return ax def plot_brillouin(self): - """Plot the Brillouin zone.""" - # get labels and lines + """Plot the Brillouin zone. + + Returns: + plt.Figure: A matplotlib figure object with the Brillouin zone. + """ + # make labels and lines labels = {} for k in self._bs[0].kpoints: if k.label: labels[k.label] = k.frac_coords lines = [] - for b in self._bs[0].branches: - lines.append( - [ - self._bs[0].kpoints[b["start_index"]].frac_coords, - self._bs[0].kpoints[b["end_index"]].frac_coords, - ] - ) + for branch in self._bs[0].branches: + kpts = self._bs[0].kpoints + start_idx, end_idx = branch["start_index"], branch["end_index"] + lines.append([kpts[start_idx].frac_coords, kpts[end_idx].frac_coords]) - plot_brillouin_zone(self._bs[0].lattice_rec, lines=lines, labels=labels) + return plot_brillouin_zone(self._bs[0].lattice_rec, lines=lines, labels=labels) class BSPlotterProjected(BSPlotter): @@ -2509,7 +2510,8 @@ def get_plot( def _rgbline(ax, k, e, red, green, blue, alpha=1, linestyles="solid"): """An RGB colored line for plotting. creation of segments based on: - http://nbviewer.ipython.org/urls/raw.github.com/dpsanders/matplotlib-examples/master/colorline.ipynb + http://nbviewer.ipython.org/urls/raw.github.com/dpsanders/matplotlib-examples/master/colorline.ipynb. + Args: ax: matplotlib axis k: x-axis data (k-points) @@ -2811,7 +2813,7 @@ def plot_seebeck_eff_mass_mu(self, temps=(300,), output="average", Lambda=0.5): using the average of the three diagonal components of the seebeck tensor. 'tensor' returns the seebeck effective mass respect to the three diagonal components of the seebeck tensor. - temps: list of temperatures of calculated seebeck. + temps: list of temperatures of calculated seebeck. Lambda: fitting parameter used to model the scattering (0.5 means constant relaxation time). @@ -2868,12 +2870,12 @@ def plot_complexity_factor_mu(self, temps=(300,), output="average", Lambda=0.5): Args: output: 'average' returns the complexity factor calculated using the average - of the three diagonal components of the seebeck and conductivity tensors. - 'tensor' returns the complexity factor respect to the three - diagonal components of seebeck and conductivity tensors. - temps: list of temperatures of calculated seebeck and conductivity. + of the three diagonal components of the seebeck and conductivity tensors. + 'tensor' returns the complexity factor respect to the three + diagonal components of seebeck and conductivity tensors. + temps: list of temperatures of calculated seebeck and conductivity. Lambda: fitting parameter used to model the scattering (0.5 means constant - relaxation time). + relaxation time). Returns: a matplotlib object @@ -4041,22 +4043,19 @@ def plot_wigner_seitz(lattice, ax: plt.Axes = None, **kwargs): Args: lattice: Lattice object - ax: matplotlib :class:`Axes` or None if a new figure should be created. + ax: matplotlib Axes or None if a new figure should be created. kwargs: kwargs passed to the matplotlib function 'plot'. Color defaults to black and linewidth to 1. Returns: matplotlib figure and matplotlib ax """ - ax, fig, plt = get_ax3d_fig_plt(ax) + ax, fig = get_ax3d_fig(ax) - if "color" not in kwargs: - kwargs["color"] = "k" - if "linewidth" not in kwargs: - kwargs["linewidth"] = 1 + kwargs.setdefault("color", "k") + kwargs.setdefault("linewidth", 1) bz = lattice.get_wigner_seitz_cell() - ax, fig, plt = get_ax3d_fig_plt(ax) for iface in range(len(bz)): # pylint: disable=C0200 for line in itertools.combinations(bz[iface], 2): for jface in range(len(bz)): @@ -4075,14 +4074,14 @@ def plot_lattice_vectors(lattice, ax: plt.Axes = None, **kwargs): Args: lattice: Lattice object - ax: matplotlib :class:`Axes` or None if a new figure should be created. + ax: matplotlib Axes or None if a new figure should be created. kwargs: kwargs passed to the matplotlib function 'plot'. Color defaults to green and linewidth to 3. Returns: matplotlib figure and matplotlib ax """ - ax, fig, plt = get_ax3d_fig_plt(ax) + ax, fig = get_ax3d_fig(ax) if "color" not in kwargs: kwargs["color"] = "g" @@ -4109,14 +4108,14 @@ def plot_path(line, lattice=None, coords_are_cartesian=False, ax: plt.Axes = Non coords_are_cartesian: Set to True if you are providing coordinates in Cartesian coordinates. Defaults to False. Requires lattice if False. - ax: matplotlib :class:`Axes` or None if a new figure should be created. + ax: matplotlib Axes or None if a new figure should be created. kwargs: kwargs passed to the matplotlib function 'plot'. Color defaults to red and linewidth to 3. Returns: matplotlib figure and matplotlib ax """ - ax, fig, plt = get_ax3d_fig_plt(ax) + ax, fig = get_ax3d_fig(ax) if "color" not in kwargs: kwargs["color"] = "r" @@ -4145,14 +4144,14 @@ def plot_labels(labels, lattice=None, coords_are_cartesian=False, ax: plt.Axes = coords_are_cartesian: Set to True if you are providing. coordinates in Cartesian coordinates. Defaults to False. Requires lattice if False. - ax: matplotlib :class:`Axes` or None if a new figure should be created. + ax: matplotlib Axes or None if a new figure should be created. kwargs: kwargs passed to the matplotlib function 'text'. Color defaults to blue and size to 25. Returns: matplotlib figure and matplotlib ax """ - ax, fig, plt = get_ax3d_fig_plt(ax) + ax, fig = get_ax3d_fig(ax) if "color" not in kwargs: kwargs["color"] = "b" @@ -4220,13 +4219,13 @@ def plot_points(points, lattice=None, coords_are_cartesian=False, fold=False, ax Requires lattice if False. fold: whether the points should be folded inside the first Brillouin Zone. Defaults to False. Requires lattice if True. - ax: matplotlib :class:`Axes` or None if a new figure should be created. + ax: matplotlib Axes or None if a new figure should be created. kwargs: kwargs passed to the matplotlib function 'scatter'. Color defaults to blue Returns: matplotlib figure and matplotlib ax """ - ax, fig, plt = get_ax3d_fig_plt(ax) + ax, fig = get_ax3d_fig(ax) if "color" not in kwargs: kwargs["color"] = "b" @@ -4253,7 +4252,7 @@ def plot_brillouin_zone_from_kpath(kpath, ax: plt.Axes = None, **kwargs): Args: kpath (HighSymmKpath): a HighSymmKPath object - ax: matplotlib :class:`Axes` or None if a new figure should be created. + ax: matplotlib Axes or None if a new figure should be created. **kwargs: provided by add_fig_kwargs decorator Returns: @@ -4277,7 +4276,7 @@ def plot_brillouin_zone( labels=None, kpoints=None, fold=False, - coords_are_cartesian=False, + coords_are_cartesian: bool = False, ax: plt.Axes = None, **kwargs, ): @@ -4293,7 +4292,7 @@ def plot_brillouin_zone( Defaults to False. Requires lattice if True. coords_are_cartesian: Set to True if you are providing coordinates in Cartesian coordinates. Defaults to False. - ax: matplotlib :class:`Axes` or None if a new figure should be created. + ax: matplotlib Axes or None if a new figure should be created. kwargs: provided by add_fig_kwargs decorator Returns: @@ -4353,7 +4352,7 @@ def plot_ellipsoid( center: the center of the ellipsoid in reciprocal coords (Default) lattice: Lattice object of the Brillouin zone rescale: factor for size scaling of the ellipsoid - ax: matplotlib :class:`Axes` or None if a new figure should be created. + ax: matplotlib Axes or None if a new figure should be created. coords_are_cartesian: Set to True if you are providing a center in Cartesian coordinates. Defaults to False. arrows: whether to plot arrows for the principal axes of the ellipsoid. Defaults to False. @@ -4399,7 +4398,7 @@ def plot_ellipsoid( [x[i, j], y[i, j], z[i, j]] = np.dot([x[i, j], y[i, j], z[i, j]], rotation) * rescale + center # add the ellipsoid to the current axes - ax, fig, plt = get_ax3d_fig_plt(ax) + ax, fig = get_ax3d_fig(ax) ax.plot_wireframe(x, y, z, **kwargs) if arrows: diff --git a/pymatgen/ext/matproj.py b/pymatgen/ext/matproj.py index 45175f07d3f..4b8e64b61f9 100644 --- a/pymatgen/ext/matproj.py +++ b/pymatgen/ext/matproj.py @@ -302,7 +302,8 @@ def get_database_version(self) -> str: where "-DD" may be optional. An additional numerical suffix might be added if multiple releases happen on the same day. - Returns: database version as a string + Returns: + str: database version """ dct = self._make_request("/api_check") return dct["version"]["db"] diff --git a/pymatgen/ext/optimade.py b/pymatgen/ext/optimade.py index 0d56f4f60a0..52900b0cd80 100644 --- a/pymatgen/ext/optimade.py +++ b/pymatgen/ext/optimade.py @@ -277,7 +277,8 @@ def get_structures_with_filter(self, optimade_filter: str) -> dict[str, dict[str Args: optimade_filter: An OPTIMADE-compliant filter - Returns: Dict of Structures keyed by that database's id system + Returns: + dict[str, Structure]: keyed by that database provider's id system """ all_snls = self.get_snls_with_filter(optimade_filter) all_structures = {} @@ -298,7 +299,8 @@ def get_snls_with_filter( optimade_filter: An OPTIMADE-compliant filter additional_response_fields: Any additional fields desired from the OPTIMADE API, - Returns: Dict of Structures keyed by that database's id system + Returns: + dict[str, Structure]: keyed by that database provider's id system """ all_snls = {} diff --git a/pymatgen/io/abinit/abiobjects.py b/pymatgen/io/abinit/abiobjects.py index d37bbbc34db..f8875af6160 100644 --- a/pymatgen/io/abinit/abiobjects.py +++ b/pymatgen/io/abinit/abiobjects.py @@ -26,23 +26,23 @@ def lattice_from_abivars(cls=None, *args, **kwargs): If acell is not given, the Abinit default is used i.e. [1,1,1] Bohr. Args: - cls: Lattice class to be instantiated. pymatgen.core.lattice.Lattice if `cls` is None + cls: Lattice class to be instantiated. Defaults to pymatgen.core.Lattice. Example: lattice_from_abivars(acell=3*[10], rprim=np.eye(3)) """ - cls = Lattice if cls is None else cls + cls = cls or Lattice kwargs.update(dict(*args)) - rprim = kwargs.get("rprim") + r_prim = kwargs.get("rprim") ang_deg = kwargs.get("angdeg") - acell = kwargs["acell"] + a_cell = kwargs["acell"] - if rprim is not None: + if r_prim is not None: if ang_deg is not None: raise ValueError("angdeg and rprimd are mutually exclusive") - rprim = np.reshape(rprim, (3, 3)) - rprimd = [float(acell[i]) * rprim[i] for i in range(3)] + r_prim = np.reshape(r_prim, (3, 3)) + rprimd = [float(a_cell[i]) * r_prim[i] for i in range(3)] # Call pymatgen constructors (note that pymatgen uses Angstrom instead of Bohr). return cls(ArrayWithUnit(rprimd, "bohr").to("ang")) @@ -58,7 +58,7 @@ def lattice_from_abivars(cls=None, *args, **kwargs): # See also http://www.abinit.org/doc/helpfiles/for-v7.8/input_variables/varbas.html#angdeg tol12 = 1e-12 pi, sin, cos, sqrt = np.pi, np.sin, np.cos, np.sqrt - rprim = np.zeros((3, 3)) + r_prim = np.zeros((3, 3)) if ( abs(ang_deg[0] - ang_deg[1]) < tol12 and abs(ang_deg[1] - ang_deg[2]) < tol12 @@ -70,26 +70,26 @@ def lattice_from_abivars(cls=None, *args, **kwargs): a2 = 2.0 / 3.0 * (1.0 - cos_ang) aa = sqrt(a2) cc = sqrt(1.0 - a2) - rprim[0, 0] = aa - rprim[0, 1] = 0.0 - rprim[0, 2] = cc - rprim[1, 0] = -0.5 * aa - rprim[1, 1] = sqrt(3.0) * 0.5 * aa - rprim[1, 2] = cc - rprim[2, 0] = -0.5 * aa - rprim[2, 1] = -sqrt(3.0) * 0.5 * aa - rprim[2, 2] = cc + r_prim[0, 0] = aa + r_prim[0, 1] = 0.0 + r_prim[0, 2] = cc + r_prim[1, 0] = -0.5 * aa + r_prim[1, 1] = sqrt(3.0) * 0.5 * aa + r_prim[1, 2] = cc + r_prim[2, 0] = -0.5 * aa + r_prim[2, 1] = -sqrt(3.0) * 0.5 * aa + r_prim[2, 2] = cc else: # Treat all the other cases - rprim[0, 0] = 1.0 - rprim[1, 0] = cos(pi * ang_deg[2] / 180.0) - rprim[1, 1] = sin(pi * ang_deg[2] / 180.0) - rprim[2, 0] = cos(pi * ang_deg[1] / 180.0) - rprim[2, 1] = (cos(pi * ang_deg[0] / 180.0) - rprim[1, 0] * rprim[2, 0]) / rprim[1, 1] - rprim[2, 2] = sqrt(1.0 - rprim[2, 0] ** 2 - rprim[2, 1] ** 2) + r_prim[0, 0] = 1.0 + r_prim[1, 0] = cos(pi * ang_deg[2] / 180.0) + r_prim[1, 1] = sin(pi * ang_deg[2] / 180.0) + r_prim[2, 0] = cos(pi * ang_deg[1] / 180.0) + r_prim[2, 1] = (cos(pi * ang_deg[0] / 180.0) - r_prim[1, 0] * r_prim[2, 0]) / r_prim[1, 1] + r_prim[2, 2] = sqrt(1.0 - r_prim[2, 0] ** 2 - r_prim[2, 1] ** 2) # Call pymatgen constructors (note that pymatgen uses Angstrom instead of Bohr). - rprimd = [float(acell[i]) * rprim[i] for i in range(3)] + rprimd = [float(a_cell[i]) * r_prim[i] for i in range(3)] return cls(ArrayWithUnit(rprimd, "bohr").to("ang")) raise ValueError(f"Don't know how to construct a Lattice from dict:\n{pformat(kwargs)}") @@ -97,7 +97,7 @@ def lattice_from_abivars(cls=None, *args, **kwargs): def structure_from_abivars(cls=None, *args, **kwargs): """ - Build a :class:`Structure` object from a dictionary with ABINIT variables. + Build a Structure object from a dictionary with ABINIT variables. Args: cls: Structure class to be instantiated. pymatgen.core.structure.Structure if cls is None @@ -220,7 +220,7 @@ def structure_to_abivars(structure, enforce_znucl=None, enforce_typat=None, **kw if len(enforce_typat) != len(structure): raise ValueError( - f"enforce_typat contains {len(enforce_typat)} entries while it should be natom: {len(structure)}" + f"enforce_typat contains {len(enforce_typat)} entries while it should be {len(structure)=}" ) if len(enforce_znucl) != n_types_atom: @@ -804,7 +804,7 @@ def gamma_centered(cls, kpts=(1, 1, 1), use_symmetries=True, use_time_reversal=T to reduce the number of independent k-points. Returns: - :class:`KSampling` object. + KSampling object. """ return cls( kpts=[kpts], @@ -834,7 +834,7 @@ def monkhorst( use_time_reversal: Use time-reversal symmetry to reduce the number of k-points. Returns: - :class:`KSampling` object. + KSampling object. """ return cls( kpts=[ngkpt], @@ -859,13 +859,13 @@ def monkhorst_automatic( Convenient static constructor for an automatic Monkhorst-Pack mesh. Args: - structure: :class:`Structure` object. + structure: Structure object. ngkpt: Subdivisions N_1, N_2 and N_3 along reciprocal lattice vectors. use_symmetries: Use spatial symmetries to reduce the number of k-points. use_time_reversal: Use time-reversal symmetry to reduce the number of k-points. Returns: - :class:`KSampling` object. + KSampling object. """ # TODO shiftk = 3 * (0.5,) @@ -889,13 +889,13 @@ def _path(cls, ndivsm, structure=None, kpath_bounds=None, comment=None): Static constructor for path in k-space. Args: - structure: :class:`Structure` object. + structure: Structure object. kpath_bounds: List with the reduced coordinates of the k-points defining the path. ndivsm: Number of division for the smallest segment. comment: Comment string. Returns: - :class:`KSampling` object. + KSampling object. """ if kpath_bounds is None: # Compute the boundaries from the input structure. @@ -1341,7 +1341,7 @@ def __init__( nband Number of bands for the Green's function w_type: Screening type sc_mode: Self-consistency mode. - hilbert: Instance of :class:`HilbertTransform` defining the parameters for the Hilber transform method. + hilbert: Instance of HilbertTransform defining the parameters for the Hilber transform method. ecutwfn: Cutoff energy for the wavefunctions (Default: ecutwfn == ecut). inclvkb: Option for the treatment of the dipole matrix elements (NC pseudos). """ @@ -1441,11 +1441,11 @@ def __init__( sc_mode: Self-consistency mode. nband: Number of bands for the Green's function ecutsigx: Cutoff energy for the exchange part of the self-energy (Ha units). - screening: :class:`Screening` instance. + screening: Screening instance. gw_qprange: Option for the automatic selection of k-points and bands for GW corrections. See Abinit docs for more detail. The default value makes the code computie the QP energies for all the point in the IBZ and one band above and one band below the Fermi level. - ppmodel: :class:`PPModel` instance with the parameters used for the plasmon-pole technique. + ppmodel: PPModel instance with the parameters used for the plasmon-pole technique. ecuteps: Cutoff energy for the screening (Ha units). ecutwfn: Cutoff energy for the wavefunctions (Default: ecutwfn == ecut). """ diff --git a/pymatgen/io/abinit/abitimer.py b/pymatgen/io/abinit/abitimer.py index f627de9bb26..277d8ff745f 100644 --- a/pymatgen/io/abinit/abitimer.py +++ b/pymatgen/io/abinit/abitimer.py @@ -9,17 +9,14 @@ import logging import os import sys -from typing import TYPE_CHECKING +import matplotlib.pyplot as plt import numpy as np from monty.string import is_string, list_strings from pymatgen.io.core import ParseError from pymatgen.util.num import minloc -from pymatgen.util.plotting import add_fig_kwargs, get_ax_fig_plt - -if TYPE_CHECKING: - import matplotlib.pyplot as plt +from pymatgen.util.plotting import add_fig_kwargs, get_ax_fig logger = logging.getLogger(__name__) @@ -253,7 +250,7 @@ def pefficiency(self): """ Analyze the parallel efficiency. - Return: :class:`ParallelEfficiency` object. + Return: ParallelEfficiency object. """ timers = self.timers() @@ -328,7 +325,7 @@ def plot_efficiency(self, key="wall_time", what="good+bad", nmax=5, ax: plt.Axes what: Specifies what to plot: `good` for sections with good parallel efficiency. `bad` for sections with bad efficiency. Options can be concatenated with `+`. nmax: Maximum number of entries in plot - ax: matplotlib :class:`Axes` or None if a new figure should be created. + ax: matplotlib Axes or None if a new figure should be created. ================ ==================================================== kwargs Meaning @@ -340,7 +337,7 @@ def plot_efficiency(self, key="wall_time", what="good+bad", nmax=5, ax: plt.Axes Returns: `matplotlib` figure """ - ax, fig, plt = get_ax_fig_plt(ax=ax) + ax, fig = get_ax_fig(ax=ax) lw = kwargs.pop("linewidth", 2.0) msize = kwargs.pop("markersize", 10) what = what.split("+") @@ -429,14 +426,14 @@ def plot_stacked_hist(self, key="wall_time", nmax=5, ax: plt.Axes = None, **kwar Args: key: Keyword used to extract data from the timers. Only the first `nmax` sections with largest value are show. - mmax: Maximum number of sections to show. Other entries are grouped together + nmax: Maximum number of sections to show. Other entries are grouped together in the `others` section. - ax: matplotlib :class:`Axes` or None if a new figure should be created. + ax: matplotlib Axes or None if a new figure should be created. Returns: `matplotlib` figure """ - ax, fig, plt = get_ax_fig_plt(ax=ax) + ax, fig = get_ax_fig(ax=ax) mpi_rank = "0" timers = self.timers(mpi_rank=mpi_rank) @@ -445,14 +442,14 @@ def plot_stacked_hist(self, key="wall_time", nmax=5, ax: plt.Axes = None, **kwar names, values = [], [] rest = np.zeros(n) - for idx, sname in enumerate(self.section_names(ordkey=key)): - sections = self.get_sections(sname) - svals = np.asarray([s.__dict__[key] for s in sections]) + for idx, sec_name in enumerate(self.section_names(ordkey=key)): + sections = self.get_sections(sec_name) + sec_vals = np.asarray([s.__dict__[key] for s in sections]) if idx < nmax: - names.append(sname) - values.append(svals) + names.append(sec_name) + values.append(sec_vals) else: - rest += svals + rest += sec_vals names.append(f"others ({nmax=})") values.append(rest) @@ -797,11 +794,12 @@ def cpuwall_histogram(self, ax: plt.Axes = None, **kwargs): Plot histogram with cpu- and wall-time on axis `ax`. Args: - ax: matplotlib :class:`Axes` or None if a new figure should be created. + ax: matplotlib Axes or None if a new figure should be created. - Returns: `matplotlib` figure + Returns: + plt.Figure: matplotlib figure """ - ax, fig, plt = get_ax_fig_plt(ax=ax) + ax, fig = get_ax_fig(ax=ax) nk = len(self.sections) ind = np.arange(nk) # the x locations for the groups @@ -833,11 +831,12 @@ def pie(self, key="wall_time", minfract=0.05, ax: plt.Axes = None, **kwargs): Args: key: Keyword used to extract data from the timer. minfract: Don't show sections whose relative weight is less that minfract. - ax: matplotlib :class:`Axes` or None if a new figure should be created. + ax: matplotlib Axes or None if a new figure should be created. - Returns: `matplotlib` figure + Returns: + plt.Figure: matplotlib figure """ - ax, fig, plt = get_ax_fig_plt(ax=ax) + ax, fig = get_ax_fig(ax=ax) # Set aspect ratio to be equal so that pie is drawn as a circle. ax.axis("equal") # Don't show section whose value is less that minfract @@ -851,13 +850,14 @@ def scatter_hist(self, ax: plt.Axes = None, **kwargs): Scatter plot + histogram. Args: - ax: matplotlib :class:`Axes` or None if a new figure should be created. + ax: matplotlib Axes or None if a new figure should be created. - Returns: `matplotlib` figure + Returns: + plt.Figure: matplotlib figure """ from mpl_toolkits.axes_grid1 import make_axes_locatable - ax, fig, plt = get_ax_fig_plt(ax=ax) + ax, fig = get_ax_fig(ax=ax) x = np.asarray(self.get_values("cpu_time")) y = np.asarray(self.get_values("wall_time")) diff --git a/pymatgen/io/abinit/inputs.py b/pymatgen/io/abinit/inputs.py index d27d06b193e..1b42e3736b4 100644 --- a/pymatgen/io/abinit/inputs.py +++ b/pymatgen/io/abinit/inputs.py @@ -950,7 +950,7 @@ def set_spin_mode(self, spin_mode): Return dictionary with the variables that have been removed. Args: - spin_mode: :class:`SpinMode` object or string. Possible values for string are: + spin_mode: SpinMode object or string. Possible values for string are: - polarized - unpolarized diff --git a/pymatgen/io/abinit/netcdf.py b/pymatgen/io/abinit/netcdf.py index 21fbd212148..6fa0432f63c 100644 --- a/pymatgen/io/abinit/netcdf.py +++ b/pymatgen/io/abinit/netcdf.py @@ -260,7 +260,7 @@ def read_structure(self, cls=Structure): return structure_from_ncdata(self, cls=cls) def read_abinit_xcfunc(self): - """Read ixc from an Abinit file. Return :class:`XcFunc` object.""" + """Read ixc from an Abinit file. Return XcFunc object.""" ixc = int(self.read_value("ixc")) return XcFunc.from_abinit_ixc(ixc) @@ -268,7 +268,7 @@ def read_abinit_hdr(self): """ Read the variables associated to the Abinit header. - Return :class:`AbinitHeader` + Return AbinitHeader """ dct = {} for hvar in _HDR_VARIABLES.values(): diff --git a/pymatgen/io/abinit/pseudos.py b/pymatgen/io/abinit/pseudos.py index 264b79727b4..56940315bd5 100644 --- a/pymatgen/io/abinit/pseudos.py +++ b/pymatgen/io/abinit/pseudos.py @@ -25,7 +25,7 @@ from pymatgen.core.periodic_table import Element from pymatgen.core.xcfunc import XcFunc from pymatgen.io.core import ParseError -from pymatgen.util.plotting import add_fig_kwargs, get_ax_fig_plt +from pymatgen.util.plotting import add_fig_kwargs, get_ax_fig if TYPE_CHECKING: from collections.abc import Iterator, Sequence @@ -191,7 +191,7 @@ def type(self) -> str: @property def element(self) -> Element: - """Pymatgen :class:`Element`.""" + """Pymatgen Element.""" try: return Element.from_Z(self.Z) except (KeyError, IndexError): @@ -325,7 +325,7 @@ def djrepo_path(self): def hint_for_accuracy(self, accuracy="normal"): """ - Returns a :class:`Hint` object with the suggested value of ecut [Ha] and + Returns 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. @@ -357,7 +357,7 @@ def has_hints(self): def open_pspsfile(self, ecut=20, pawecutdg=None): """ Calls Abinit to compute the internal tables for the application of the - pseudopotential part. Returns :class:`PspsFile` object providing methods + pseudopotential part. Returns PspsFile object providing methods to plot and analyze the data or None if file is not found or it's not readable. Args: @@ -468,7 +468,7 @@ def __init__(self, path, header): """ Args: path: Filename. - header: :class:`AbinitHeader` instance. + header: AbinitHeader instance. """ self.path = path self.header = header @@ -1010,7 +1010,7 @@ def paw_header(filename, ppdesc): class PseudoParseError(ParseError): - """Base Error class for the exceptions raised by :class:`PseudoParser`.""" + """Base Error class for the exceptions raised by PseudoParser.""" class PseudoParser: @@ -1421,12 +1421,12 @@ def plot_densities(self, ax: plt.Axes = None, **kwargs): Plot the PAW densities. Args: - ax: matplotlib :class:`Axes` or None if a new figure should be created. + ax: matplotlib Axes or None if a new figure should be created. Returns: `matplotlib` figure """ - ax, fig, plt = get_ax_fig_plt(ax) + ax, fig = get_ax_fig(ax) ax.grid(True) ax.set_xlabel("r [Bohr]") @@ -1447,13 +1447,14 @@ def plot_waves(self, ax: plt.Axes = None, fontsize=12, **kwargs): Plot the AE and the pseudo partial waves. Args: - ax: matplotlib :class:`Axes` or None if a new figure should be created. + ax: matplotlib Axes or None if a new figure should be created. fontsize: fontsize for legends and titles - Returns: `matplotlib` figure + Returns: + plt.Figure: matplotlib figure """ # pylint: disable=E1101 - ax, fig, plt = get_ax_fig_plt(ax) + ax, fig = get_ax_fig(ax) ax.grid(True) ax.set_xlabel("r [Bohr]") @@ -1478,12 +1479,13 @@ def plot_projectors(self, ax: plt.Axes = None, fontsize=12, **kwargs): Plot the PAW projectors. Args: - ax: matplotlib :class:`Axes` or None if a new figure should be created. + ax: matplotlib Axes or None if a new figure should be created. - Returns: `matplotlib` figure + Returns: + plt.Figure: matplotlib figure """ # pylint: disable=E1101 - ax, fig, plt = get_ax_fig_plt(ax) + ax, fig = get_ax_fig(ax) ax.grid(True) ax.set_xlabel("r [Bohr]") ax.set_ylabel(r"$r\tilde p\, [Bohr]^{-\frac{1}{2}}$") @@ -1559,7 +1561,7 @@ class PseudoTable(collections.abc.Sequence, MSONable): @classmethod def as_table(cls, items): - """Return an instance of :class:`PseudoTable` from the iterable items.""" + """Return an instance of PseudoTable from the iterable items.""" if isinstance(items, cls): return items return cls(items) @@ -1575,7 +1577,7 @@ def from_dir(cls, top, exts=None, exclude_dirs="_*"): we try to open all files in top exclude_dirs: Wildcard used to exclude directories. - return: :class:`PseudoTable` sorted by atomic number Z. + return: PseudoTable sorted by atomic number Z. """ pseudos = [] @@ -1772,12 +1774,12 @@ def pseudos_with_symbols(self, symbols): def select_symbols(self, symbols, ret_list=False): """ - Return a :class:`PseudoTable` with the pseudopotentials with the given list of chemical symbols. + Return a PseudoTable with the pseudopotentials with the given list of chemical symbols. Args: symbols: str or list of symbols Prepend the symbol string with "-", to exclude pseudos. - ret_list: if True a list of pseudos is returned instead of a :class:`PseudoTable` + ret_list: if True a list of pseudos is returned instead of a PseudoTable """ symbols = list_strings(symbols) exclude = symbols[0].startswith("-") @@ -1804,10 +1806,10 @@ def select_symbols(self, symbols, ret_list=False): def get_pseudos_for_structure(self, structure: Structure): """ - Return the list of :class:`Pseudo` objects to be used for this :class:`Structure`. + Return the list of Pseudo objects to be used for this Structure. Args: - structure: pymatgen :class:`Structure`. + structure: pymatgen Structure. Raises: `ValueError` if one of the chemical symbols is not found or @@ -1860,7 +1862,7 @@ def sorted(self, attrname, reverse=False): return self.__class__([self[a[0]] for a in sorted(attrs, key=lambda t: t[1], reverse=reverse)]) def sort_by_z(self): - """Return a new :class:`PseudoTable` with pseudos sorted by Z.""" + """Return a new PseudoTable with pseudos sorted by Z.""" return self.__class__(sorted(self, key=lambda p: p.Z)) def select(self, condition) -> PseudoTable: @@ -1868,7 +1870,7 @@ def select(self, condition) -> PseudoTable: Args: condition: - Function that accepts a :class:`Pseudo` object and returns True or False. + Function that accepts a Pseudo object and returns True or False. Returns: PseudoTable: New PseudoTable instance with pseudos for which condition is True. diff --git a/pymatgen/io/cif.py b/pymatgen/io/cif.py index ff7f2f46476..5af40c2daa3 100644 --- a/pymatgen/io/cif.py +++ b/pymatgen/io/cif.py @@ -180,6 +180,7 @@ def from_str(cls, string): Reads CifBlock from string. :param string: String representation. + Returns: CifBlock """ @@ -250,6 +251,7 @@ def from_str(cls, string): Reads CifFile from a string. :param string: String representation. + Returns: CifFile """ @@ -1202,6 +1204,7 @@ def get_bibtex_string(self): """ Get BibTeX reference from CIF file. :param data: + Returns: BibTeX string. """ diff --git a/pymatgen/io/common.py b/pymatgen/io/common.py index 3afbdde1418..2fb9ea2bb28 100644 --- a/pymatgen/io/common.py +++ b/pymatgen/io/common.py @@ -270,7 +270,7 @@ def to_hdf5(self, filename): VolumetricData.structure -> f["Z"]: Sequence of atomic numbers f["fcoords"]: Fractional coords - f["lattice"]: Lattice in the pymatgen.core.lattice.Lattice matrix + f["lattice"]: Lattice in the pymatgen.core.Lattice matrix format f.attrs["structure_json"]: String of json representation diff --git a/pymatgen/io/cp2k/inputs.py b/pymatgen/io/cp2k/inputs.py index 63f03782b73..5010e3e8d76 100644 --- a/pymatgen/io/cp2k/inputs.py +++ b/pymatgen/io/cp2k/inputs.py @@ -400,12 +400,11 @@ def add(self, other): def get(self, d, default=None): """ Similar to get for dictionaries. This will attempt to retrieve the - section or keyword matching d. Will not raise an error if d does not - exist. + section or keyword matching d. Will not raise an error if d does not exist. Args: - d: the key to retrieve, if present - default: what to return if d is not found + d: the key to retrieve, if present + default: what to return if d is not found """ kw = self.get_keyword(d) if kw: diff --git a/pymatgen/io/exciting/inputs.py b/pymatgen/io/exciting/inputs.py index 6c263e7f28b..07e630849f3 100644 --- a/pymatgen/io/exciting/inputs.py +++ b/pymatgen/io/exciting/inputs.py @@ -38,7 +38,7 @@ class ExcitingInput(MSONable): def __init__(self, structure: Structure, title=None, lockxyz=None): """ Args: - structure (Structure): Structure object. + structure (Structure): Structure object. title (str): Optional title for exciting input. Defaults to unit cell formula of structure. Defaults to None. lockxyz (Nx3 array): bool values for selective dynamics, diff --git a/pymatgen/io/fiesta.py b/pymatgen/io/fiesta.py index 0c0c38767f4..aff42edc132 100644 --- a/pymatgen/io/fiesta.py +++ b/pymatgen/io/fiesta.py @@ -86,6 +86,7 @@ def as_dict(self): def from_dict(cls, d): """ :param d: Dict representation. + Returns: Nwchem2Fiesta """ diff --git a/pymatgen/io/lammps/inputs.py b/pymatgen/io/lammps/inputs.py index 4d7238923fa..28ff5962365 100644 --- a/pymatgen/io/lammps/inputs.py +++ b/pymatgen/io/lammps/inputs.py @@ -318,7 +318,7 @@ def merge_stages(self, stage_names: list[str]): The others will appear in the same order as provided in the list. Other non-merged stages will follow. Args: - stage_names (list): list of strings giving the names of the stages to be merged. + stage_names (list): list of strings giving the names of the stages to be merged. """ if not all(stage in self.stages_names for stage in stage_names): raise ValueError("At least one of the stages to be merged is not in the LammpsInputFile.") @@ -484,10 +484,11 @@ def get_str(self, ignore_comments: bool = False, keep_stages: bool = True) -> st Args: ignore_comments (bool): True if only the commands should be kept from the InputFile. keep_stages (bool): If True, the string is formatted in a block structure with stage names - and newlines that differentiate commands in the respective stages of the InputFile. - If False, stage names are not printed and all commands appear in a single block. + and newlines that differentiate commands in the respective stages of the InputFile. + If False, stage names are not printed and all commands appear in a single block. - Returns: String representation of the LammpsInputFile. + Returns: + str: String representation of the LammpsInputFile. """ lammps_input = f"# LAMMPS input generated from LammpsInputFile with pymatgen v{CURRENT_VER}\n" if not keep_stages: diff --git a/pymatgen/io/lmto.py b/pymatgen/io/lmto.py index f03aa9ae8f2..e5c7777a67c 100644 --- a/pymatgen/io/lmto.py +++ b/pymatgen/io/lmto.py @@ -359,14 +359,13 @@ def _get_bond_data(line): a COPL header line. The site indices are zero-based, so they can be easily used with a Structure object. - Example header line: Fe-1/Fe-1-tr(-1,-1,-1) : 2.482 Ang. + Example header line: Fe-1/Fe-1-tr(-1,-1,-1) : 2.482 Ang. Args: line: line in the COHPCAR header describing the bond. Returns: - The bond label, the bond length and a tuple of the site - indices. + The bond label, the bond length and a tuple of the site indices. """ line = line.split() length = float(line[2]) diff --git a/pymatgen/io/lobster/inputs.py b/pymatgen/io/lobster/inputs.py index 1cb8213278f..0ddb1d139a7 100644 --- a/pymatgen/io/lobster/inputs.py +++ b/pymatgen/io/lobster/inputs.py @@ -393,8 +393,9 @@ def get_all_possible_basis_functions( address_basis_file_min: path to file with the minimum required basis by the POTCAR address_basis_file_max: path to file with the largest possible basis of the POTCAR. - Returns: List of dictionaries that can be used to create new Lobsterin objects in - standard_calculations_from_vasp_files as dict_for_basis + Returns: + list[dict]: Can be used to create new Lobsterin objects in + standard_calculations_from_vasp_files as dict_for_basis """ max_basis = Lobsterin.get_basis( structure=structure, @@ -830,7 +831,8 @@ def get_all_possible_basis_combinations(min_basis: list, max_basis: list) -> lis min_basis: list of basis entries: e.g., ['Si 3p 3s '] max_basis: list of basis entries: e.g., ['Si 3p 3s ']. - Returns: all possible combinations of basis functions, e.g. [['Si 3p 3s']] + Returns: + list[list[str]]: all possible combinations of basis functions, e.g. [['Si 3p 3s']] """ max_basis_lists = [x.split() for x in max_basis] min_basis_lists = [x.split() for x in min_basis] diff --git a/pymatgen/io/lobster/lobsterenv.py b/pymatgen/io/lobster/lobsterenv.py index 5747edb1590..44341a83cdb 100644 --- a/pymatgen/io/lobster/lobsterenv.py +++ b/pymatgen/io/lobster/lobsterenv.py @@ -217,7 +217,8 @@ def anion_types(self): """ Return the types of anions present in crystal structure as a set - Returns: set of Element describing anions in the crystal structure. + Returns: + set[Element]: describing anions in the crystal structure. """ if self.valences is None: raise ValueError("No cations and anions defined") @@ -264,7 +265,8 @@ def get_light_structure_environment(self, only_cation_environments=False, only_i only_cation_environments: only data for cations will be returned only_indices: will only evaluate the list of isites in this list - Returns: LobsterLightStructureEnvironments Object + Returns: + LobsterLightStructureEnvironments """ lgf = LocalGeometryFinder() lgf.setup_structure(structure=self.structure) @@ -370,7 +372,8 @@ def get_info_icohps_to_neighbors(self, isites=None, onlycation_isites=True): isites: list of site ids. If isite==None, all isites will be used to add the icohps of the neighbors onlycation_isites: if True and if isite==None, it will only analyse the sites of the cations - Returns: ICOHPNeighborsInfo + Returns: + ICOHPNeighborsInfo """ if self.valences is None and onlycation_isites: raise ValueError("No valences are provided") @@ -477,8 +480,9 @@ def get_info_cohps_to_neighbors( per_bond: will normalize per bond summed_spin_channels: will sum all spin channels - Returns: label for cohp (str), CompleteCohp object which describes all cohps (coops or cobis) of the sites - as given by isites and the other parameters + Returns: + str: label for cohp (str), CompleteCohp object which describes all cohps (coops or cobis) + of the sites as given by isites and the other parameters """ # TODO: add options for orbital-resolved cohps summed_icohps, list_icohps, number_bonds, labels, atoms, final_isites = self.get_info_icohps_to_neighbors( @@ -585,7 +589,8 @@ def get_info_icohps_between_neighbors(self, isites=None, onlycation_isites=True) isites: list of site ids, if isite==None, all isites will be used onlycation_isites: will only use cations, if isite==None - Returns: ICOHPNeighborsInfo + Returns + ICOHPNeighborsInfo """ lowerlimit = self.lowerlimit upperlimit = self.upperlimit @@ -1073,14 +1078,15 @@ def _get_icohps(icohpcollection, isite, lowerlimit, upperlimit, only_bonds_to): ) @staticmethod - def _get_atomnumber(atomstring): + def _get_atomnumber(atomstring) -> int: """ Return the number of the atom within the initial POSCAR (e.g., Return 0 for "Na1"). Args: atomstring: string such as "Na1" - Returns: integer indicating the position in the POSCAR + Returns: + int: indicating the position in the POSCAR """ return int(LobsterNeighbors._split_string(atomstring)[1]) - 1 @@ -1118,7 +1124,8 @@ def _adapt_extremum_to_add_cond(self, list_icohps, percentage): Args: list_icohps: can be a list of icohps or icobis or icobis - Returns: min value of input list of icohps / max value of input list of icobis or icobis + Returns: + float: min value of input list of icohps / max value of input list of icobis or icobis """ which_extr = min if not self.are_coops and not self.are_cobis else max @@ -1142,7 +1149,9 @@ def _get_limit_from_extremum( adapt_extremum_to_add_cond: should the extrumum be adapted to the additional condition additional_condition: additional condition to determine which bonds are relevant - Returns: [-inf, min(strongest_icohp*0.15,-noise_cutoff)] / [max(strongest_icohp*0.15, noise_cutoff),inf] + Returns: + tuple[float, float]: [-inf, min(strongest_icohp*0.15,-noise_cutoff)] / [max(strongest_icohp*0.15, + noise_cutoff), inf] """ if not adapt_extremum_to_add_cond or additional_condition == 0: @@ -1260,7 +1269,8 @@ def from_Lobster( list_neighisite: list of neighboring isites (number of a site) valences: list of valences - Returns: LobsterLightStructureEnvironments + Returns: + LobsterLightStructureEnvironments """ strategy = None valences_origin = "user-defined" @@ -1348,6 +1358,7 @@ def uniquely_determines_coordination_environments(self): def as_dict(self): """ Bson-serializable dict representation of the LightStructureEnvironments object. + Returns: Bson-serializable dict representation of the LightStructureEnvironments object. """ diff --git a/pymatgen/io/lobster/outputs.py b/pymatgen/io/lobster/outputs.py index 4eaabdb82f0..9acf023742a 100644 --- a/pymatgen/io/lobster/outputs.py +++ b/pymatgen/io/lobster/outputs.py @@ -598,6 +598,7 @@ def __init__(self, filename: str = "CHARGE.lobster"): def get_structure_with_charges(self, structure_filename): """ Get a Structure with Mulliken and Loewdin charges as site properties + Args: structure_filename: filename of POSCAR @@ -1136,6 +1137,7 @@ def __init__(self, filename: str = "bandOverlaps.lobster"): def _read(self, contents: list, spin_numbers: list): """ Will read in all contents of the file + Args: contents: list of strings spin_numbers: list of spin numbers depending on `Lobster` version. @@ -1198,7 +1200,7 @@ def has_good_quality_check_occupied_bands( Args: number_occ_bands_spin_up (int): number of occupied bands of spin up number_occ_bands_spin_down (int): number of occupied bands of spin down - spin_polarized (bool): If True, then it was a spin polarized calculation + spin_polarized (bool): If True, then it was a spin polarized calculation limit_deviation (float): limit of the maxDeviation Returns: @@ -1274,6 +1276,7 @@ def __init__(self, filename: str = "GROSSPOP.lobster"): def get_structure_with_total_grosspop(self, structure_filename: str) -> Structure: """ Get a Structure with Mulliken and Loewdin total grosspopulations as site properties + Args: structure_filename (str): filename of POSCAR @@ -1405,7 +1408,8 @@ def get_volumetricdata_real(self): """ Will return a VolumetricData object including the real part of the wave function. - Returns: VolumetricData object + Returns: + VolumetricData """ if not hasattr(self, "volumetricdata_real"): self.set_volumetric_data(self.grid, self.structure) @@ -1415,7 +1419,8 @@ def get_volumetricdata_imaginary(self): """ Will return a VolumetricData object including the imaginary part of the wave function. - Returns: VolumetricData object + Returns: + VolumetricData """ if not hasattr(self, "volumetricdata_imaginary"): self.set_volumetric_data(self.grid, self.structure) @@ -1425,7 +1430,8 @@ def get_volumetricdata_density(self): """ Will return a VolumetricData object including the imaginary part of the wave function. - Returns: VolumetricData object + Returns: + VolumetricData """ if not hasattr(self, "volumetricdata_density"): self.set_volumetric_data(self.grid, self.structure) @@ -1532,6 +1538,7 @@ def __init__(self, filename: str = "SitePotentials.lobster"): def get_structure_with_site_potentials(self, structure_filename): """ Get a Structure with Mulliken and Loewdin charges as site properties + Args: structure_filename: filename of POSCAR diff --git a/pymatgen/io/phonopy.py b/pymatgen/io/phonopy.py index caf43357687..b1d26bc908d 100644 --- a/pymatgen/io/phonopy.py +++ b/pymatgen/io/phonopy.py @@ -429,8 +429,8 @@ def get_gruneisenparameter(gruneisen_path, structure=None, structure_path=None) structure: pymatgen Structure object structure_path: path to structure in a file (e.g., POSCAR) - Returns: GruneisenParameter object - + Returns: + GruneisenParameter """ gruneisen_dict = loadfn(gruneisen_path) diff --git a/pymatgen/io/prismatic.py b/pymatgen/io/prismatic.py index 4b2644a9cc5..5a1c0e19421 100644 --- a/pymatgen/io/prismatic.py +++ b/pymatgen/io/prismatic.py @@ -31,8 +31,9 @@ def to_string(cls, *args, **kwargs): def to_str(self) -> str: """ - Returns: Prismatic XYZ file. This is similar to XYZ format - but has specific requirements for extra fields, headers, etc. + Returns: + str: Prismatic XYZ file. This is similar to XYZ format + but has specific requirements for extra fields, headers, etc. """ lattice = self.structure.lattice lines = [self.comment, " ".join(map(str, lattice.lengths))] diff --git a/pymatgen/io/res.py b/pymatgen/io/res.py index 9a241141dc6..3b05ce6e173 100644 --- a/pymatgen/io/res.py +++ b/pymatgen/io/res.py @@ -375,7 +375,7 @@ def structure(self) -> Structure: class AirssProvider(ResProvider): """ - Provides access to the res file as does :class:`ResProvider`. This class additionally provides + Provides access to the res file as does ResProvider. This class additionally provides access to fields in the TITL entry and various other fields found in the REM entries that AIRSS puts in the file. Values in the TITL entry that AIRSS could not get end up as 0. If the TITL entry is malformed, empty, or missing then attempting to construct this class @@ -388,7 +388,7 @@ class AirssProvider(ResProvider): The :attr:`parse_rems` attribute controls whether functions that fail to retrieve information from the REM entries should return ``None``. If this is set to ``"strict"``, - then a :class:`ParseError` may be raised, but the return value will not be ``None``. + then a ParseError may be raised, but the return value will not be ``None``. If it is set to ``"gentle"``, then ``None`` will be returned instead of raising an exception. This setting applies to all methods of this class that are typed to return an Optional type. Default is ``"gentle"``. diff --git a/pymatgen/io/vasp/inputs.py b/pymatgen/io/vasp/inputs.py index f374239ba29..4f837c1f4af 100644 --- a/pymatgen/io/vasp/inputs.py +++ b/pymatgen/io/vasp/inputs.py @@ -560,6 +560,7 @@ def as_dict(self) -> dict: def from_dict(cls, d: dict) -> Poscar: """ :param d: Dict representation. + Returns: Poscar """ @@ -681,6 +682,7 @@ def as_dict(self) -> dict: def from_dict(cls, d) -> Incar: """ :param d: Dict representation. + Returns: Incar """ @@ -1555,6 +1557,7 @@ def as_dict(self): def from_dict(cls, d): """ :param d: Dict representation. + Returns: Kpoints """ @@ -1856,6 +1859,7 @@ def from_file(filename: str) -> PotcarSingle: Reads PotcarSingle from file. :param filename: Filename. + Returns: PotcarSingle. """ @@ -2365,6 +2369,7 @@ def as_dict(self): def from_dict(cls, d): """ :param d: Dict representation. + Returns: VaspInput """ diff --git a/pymatgen/io/vasp/outputs.py b/pymatgen/io/vasp/outputs.py index b21bc8dd2a3..b0c3144dd88 100644 --- a/pymatgen/io/vasp/outputs.py +++ b/pymatgen/io/vasp/outputs.py @@ -1018,7 +1018,8 @@ def get_trajectory(self): representation of self.structures into a single object. Forces are added to the Trajectory as site properties. - Returns: a Trajectory + Returns: + Trajectory: from pymatgen.core.trajectory """ # required due to circular imports # TODO: fix pymatgen.core.trajectory so it does not load from io.vasp(!) @@ -3943,9 +3944,8 @@ def concatenate(self, filename, ionicstep_start=1, ionicstep_end=None): filename (str): Filename of XDATCAR file to be concatenated. ionicstep_start (int): Starting number of ionic step. ionicstep_end (int): Ending number of ionic step. - TODO(rambalachandran): - Requires a check to ensure if the new concatenating file has the - same lattice structure and atoms as the Xdatcar class. + TODO (rambalachandran): Requires a check to ensure if the new concatenating file + has the same lattice structure and atoms as the Xdatcar class. """ preamble = None coords_str = [] @@ -4499,15 +4499,13 @@ def evaluate_wavefunc(self, kpoint: int, band: int, r: np.ndarray, spin: int = 0 preferred method of evaluation (see Wavecar.fft_mesh). Args: - kpoint (int): the index of the kpoint where the wavefunction - will be evaluated - band (int): the index of the band where the wavefunction will be - evaluated + kpoint (int): the index of the kpoint where the wavefunction will be evaluated + band (int): the index of the band where the wavefunction will be evaluated r (np.array): the position where the wavefunction will be evaluated - spin (int): spin index for the desired wavefunction (only for - ISPIN = 2, default = 0) + spin (int): spin index for the desired wavefunction (only for + ISPIN = 2, default = 0) spinor (int): component of the spinor that is evaluated (only used - if vasp_type == 'ncl') + if vasp_type == 'ncl') Returns: a complex value corresponding to the evaluation of the wavefunction @@ -4535,16 +4533,14 @@ def fft_mesh(self, kpoint: int, band: int, spin: int = 0, spinor: int = 0, shift evals = np.fft.ifftn(mesh) Args: - kpoint (int): the index of the kpoint where the wavefunction - will be evaluated - band (int): the index of the band where the wavefunction will be - evaluated - spin (int): the spin of the wavefunction for the desired - wavefunction (only for ISPIN = 2, default = 0) + kpoint (int): the index of the kpoint where the wavefunction will be evaluated + band (int): the index of the band where the wavefunction will be evaluated + spin (int): the spin of the wavefunction for the desired + wavefunction (only for ISPIN = 2, default = 0) spinor (int): component of the spinor that is evaluated (only used - if vasp_type == 'ncl') + if vasp_type == 'ncl') shift (bool): determines if the zero frequency coefficient is - placed at index (0, 0, 0) or centered + placed at index (0, 0, 0) or centered Returns: a numpy ndarray representing the 3D mesh of coefficients @@ -4891,10 +4887,7 @@ def from_binary(cls, filename, data_type="complex64"): with open(filename, "rb") as fp: def readData(dtype): - """ - Read records from Fortran binary file - and convert to np.array of given dtype. - """ + """Read records from Fortran binary file and convert to np.array of given dtype.""" data = b"" while True: prefix = np.fromfile(fp, dtype=np.int32, count=1)[0] diff --git a/pymatgen/io/vasp/sets.py b/pymatgen/io/vasp/sets.py index c797e0408f9..d86117cc947 100644 --- a/pymatgen/io/vasp/sets.py +++ b/pymatgen/io/vasp/sets.py @@ -2245,7 +2245,7 @@ def __init__( :param auto_dipole: :param set_mix: :param sort_structure: - :param kwargs: Other kwargs supported by :class:`DictSet`. + :param kwargs: Other kwargs supported by DictSet. """ super().__init__(structure, MPRelaxSet.CONFIG, sort_structure=sort_structure, **kwargs) @@ -2322,6 +2322,7 @@ def kpoints(self): def as_dict(self, verbosity=2): """ :param verbosity: Verbosity of dict. E.g., whether to include Structure. + Returns: MSONable dict """ @@ -2352,7 +2353,7 @@ def __init__(self, structure: Structure | None = None, k_product=40, slab_mode=F by default. Note that it does *not* override user_incar_settings, which can be set by the user to be anything desired. **kwargs: - Other kwargs supported by :class:`MPRelaxSet`. + Other kwargs supported by MPRelaxSet. """ super().__init__(structure, MPRelaxSet.CONFIG, **kwargs) self.k_product = k_product @@ -2436,7 +2437,7 @@ def __init__(self, structure: Structure | None = None, **kwargs) -> None: Args: structure (Structure): input structure. user_potcar_functional (str): choose from "PBE_52" and "PBE_54". - **kwargs: Other kwargs supported by :class:`DictSet`. + **kwargs: Other kwargs supported by DictSet. """ kwargs.setdefault("user_potcar_functional", "PBE_52") @@ -2456,7 +2457,7 @@ def __init__(self, structures, unset_encut=False, **kwargs): Args: structures: List of Structure objects. unset_encut (bool): Whether to unset ENCUT. - **kwargs: Other kwargs supported by :class:`DictSet`. + **kwargs: Other kwargs supported by DictSet. """ if len(structures) < 3: raise ValueError("You need at least 3 structures for an NEB.") @@ -2577,7 +2578,7 @@ def __init__( parameter. Defaults to 2fs. spin_polarized (bool): Whether to do spin polarized calculations. The ISPIN parameter. Defaults to False. - **kwargs: Other kwargs supported by :class:`DictSet`. + **kwargs: Other kwargs supported by DictSet. """ # MD default settings defaults = { @@ -2664,7 +2665,7 @@ def __init__( parameter. Defaults to 2fs. spin_polarized (bool): Whether to do spin polarized calculations. The ISPIN parameter. Defaults to False. - **kwargs: Other kwargs supported by :class:`DictSet`. + **kwargs: Other kwargs supported by DictSet. """ # MD default settings defaults = { @@ -2754,7 +2755,7 @@ def __init__( parameter. Defaults to 2fs. spin_polarized (bool): Whether to do spin polarized calculations. The ISPIN parameter. Defaults to False. - **kwargs: Other kwargs supported by :class:`DictSet`. + **kwargs: Other kwargs supported by DictSet. """ super().__init__(structure, start_temp, end_temp, nsteps, time_step, spin_polarized, **kwargs) @@ -2815,7 +2816,7 @@ def __init__(self, structure: Structure | None = None, **kwargs): vdw (str): set "rVV10" to enable SCAN+rVV10, which is a versatile van der Waals density functional by combing the SCAN functional with the rVV10 non-local correlation functional. - **kwargs: Other kwargs supported by :class:`DictSet`. + **kwargs: Other kwargs supported by DictSet. """ # choose PBE_52 unless the user specifies something else kwargs.setdefault("user_potcar_functional", "PBE_52") @@ -2869,7 +2870,7 @@ def __init__( in pymatgen.io.lobster.lobster_basis user_potcar_settings (dict): dict including potcar settings for all elements in structure, e.g. {"Fe": "Fe_pv", "O": "O"}; if not supplied, a standard basis is used. - **kwargs: Other kwargs supported by :class:`DictSet`. + **kwargs: Other kwargs supported by DictSet. """ warnings.warn("Make sure that all parameters are okay! This is a brand new implementation.") @@ -3340,6 +3341,7 @@ def override_from_prev_calc(self, prev_calc_dir=".", **kwargs): def from_prev_calc(cls, prev_calc_dir, mode, **kwargs): """ Generate a set of VASP input files for absorption calculation + Args: prev_calc_dir (str): The directory contains the outputs( vasprun.xml of previous vasp run. diff --git a/pymatgen/io/xtb/inputs.py b/pymatgen/io/xtb/inputs.py index 76a3900da21..d682beaeaf6 100644 --- a/pymatgen/io/xtb/inputs.py +++ b/pymatgen/io/xtb/inputs.py @@ -73,9 +73,8 @@ def constrains_template(molecule, reference_fnm, constraints) -> str: :param reference_fnm: Name of file containing reference structure in same directory :param constraints: - Dictionary of common editable parameters for .constrains file. - {"atoms": [List of 1-indexed atoms to fix], "force_constant": - float] + Dictionary of common editable parameters for .constrains file. + {"atoms": [List of 1-indexed atoms to fix], "force_constant": float] Returns: str: for .constrains file diff --git a/pymatgen/phonon/bandstructure.py b/pymatgen/phonon/bandstructure.py index 0aef1a4b0b2..0eb76b31367 100644 --- a/pymatgen/phonon/bandstructure.py +++ b/pymatgen/phonon/bandstructure.py @@ -582,7 +582,8 @@ def from_dict(cls, dct): Args: dct: Dict representation. - Returns: PhononBandStructureSymmLine + Returns: + PhononBandStructureSymmLine """ lattice_rec = Lattice(dct["lattice_rec"]["matrix"]) eigendisplacements = ( diff --git a/pymatgen/phonon/gruneisen.py b/pymatgen/phonon/gruneisen.py index 389e8a990ad..5811dd33196 100644 --- a/pymatgen/phonon/gruneisen.py +++ b/pymatgen/phonon/gruneisen.py @@ -376,7 +376,8 @@ def from_dict(cls, dct): Args: dct: Dict representation. - Returns: GruneisenPhononBandStructureSymmLine + Returns: + GruneisenPhononBandStructureSymmLine """ lattice_rec = Lattice(dct["lattice_rec"]["matrix"]) eigendisplacements = ( diff --git a/pymatgen/phonon/plotter.py b/pymatgen/phonon/plotter.py index 97338d5facb..f0c063856af 100644 --- a/pymatgen/phonon/plotter.py +++ b/pymatgen/phonon/plotter.py @@ -13,7 +13,7 @@ from pymatgen.electronic_structure.plotter import plot_brillouin_zone from pymatgen.phonon.bandstructure import PhononBandStructureSymmLine from pymatgen.phonon.gruneisen import GruneisenPhononBandStructureSymmLine -from pymatgen.util.plotting import add_fig_kwargs, get_ax_fig_plt, pretty_plot +from pymatgen.util.plotting import add_fig_kwargs, get_ax_fig, pretty_plot logger = logging.getLogger(__name__) @@ -650,7 +650,7 @@ def _plot_thermo( temperatures: a list of temperatures factor: a multiplicative factor applied to the thermodynamic property calculated. Used to change the units. - ax: matplotlib :class:`Axes` or None if a new figure should be created. + ax: matplotlib Axes or None if a new figure should be created. ylabel: label for the y axis label: label of the plot ylim: tuple specifying the y-axis limits. @@ -659,7 +659,7 @@ def _plot_thermo( Returns: plt.figure: matplotlib figure """ - ax, fig, plt = get_ax_fig_plt(ax) + ax, fig = get_ax_fig(ax) values = [] @@ -823,20 +823,23 @@ class GruneisenPlotter: """Class to plot Gruneisenparameter Object.""" def __init__(self, gruneisen): - """Class to plot information from Gruneisenparameter Object + """Class to plot information from Gruneisenparameter Object. + Args: gruneisen: GruneisenParameter Object. """ self._gruneisen = gruneisen def get_plot(self, marker="o", markersize=None, units="thz"): - """Will produce a plot + """Will produce a plot. + Args: marker: marker for the depiction markersize: size of the marker units: unit for the plots, accepted units: thz, ev, mev, ha, cm-1, cm^-1. - Returns: plot + Returns: + plt.Axes: matplotlib axes object """ u = freq_units(units) @@ -849,29 +852,26 @@ def get_plot(self, marker="o", markersize=None, units="thz"): ax.set_ylabel(r"$\mathrm{Grüneisen\ parameter}$") n = len(ys) - 1 - for i, (x, y) in enumerate(zip(xs, ys)): - color = (1.0 / n * i, 0, 1.0 / n * (n - i)) + for idx, (xi, yi) in enumerate(zip(xs, ys)): + color = (1.0 / n * idx, 0, 1.0 / n * (n - idx)) - if markersize: - ax.plot(x, y, marker, color=color, markersize=markersize) - else: - ax.plot(x, y, marker, color=color) + ax.plot(xi, yi, marker, color=color, markersize=markersize) plt.tight_layout() return ax def show(self, units="thz"): - """Will show the plot + """Will show the plot. + Args: units: units for the plot, accepted units: thz, ev, mev, ha, cm-1, cm^-1. - - Returns: plot """ self.get_plot(units=units) plt.show() def save_plot(self, filename, img_format="pdf", units="thz"): - """Will save the plot to a file + """Will save the plot to a file. + Args: filename: name of the filename img_format: format of the saved plot diff --git a/pymatgen/phonon/thermal_displacements.py b/pymatgen/phonon/thermal_displacements.py index 658eb4254da..eb96b39e94c 100644 --- a/pymatgen/phonon/thermal_displacements.py +++ b/pymatgen/phonon/thermal_displacements.py @@ -122,7 +122,9 @@ def get_reduced_matrix(thermal_displacement): @property def Ustar(self): """Computation as described in R. W. Grosse-Kunstleve, P. D. Adams, J Appl Cryst 2002, 35, 477-480. - Returns: Ustar as a numpy array, first dimension are the atoms in the structure. + + Returns: + np.array: Ustar as array. First dimension are the atoms in the structure. """ A = self.structure.lattice.matrix.T Ainv = np.linalg.inv(A) @@ -135,7 +137,9 @@ def Ustar(self): @property def Ucif(self): """Computation as described in R. W. Grosse-Kunstleve, P. D. Adams, J Appl Cryst 2002, 35, 477-480. - Returns: Ucif as a numpy array, first dimension are the atoms in the structure. + + Returns: + np.array: Ucif as array. First dimension are the atoms in the structure. """ if self.thermal_displacement_matrix_cif is None: # computation as described in R. W. Grosse-Kunstleve, P. D. Adams, J Appl Cryst 2002, 35, 477-480. @@ -155,7 +159,9 @@ def Ucif(self): @property def B(self): """Computation as described in R. W. Grosse-Kunstleve, P. D. Adams, J Appl Cryst 2002, 35, 477-480. - Returns: B as a numpy array, first dimension are the atoms in the structure. + + Returns: + np.array: First dimension are the atoms in the structure. """ B = [] for mat in self.Ucif: @@ -166,7 +172,9 @@ def B(self): @property def beta(self): """Computation as described in R. W. Grosse-Kunstleve, P. D. Adams, J Appl Cryst 2002, 35, 477-480. - Returns: beta as a numpy array, first dimension are the atoms in the structure. + + Returns: + np.array: First dimension are the atoms in the structure. """ # will compute beta based on Ustar beta = [] @@ -178,7 +186,9 @@ def beta(self): @property def U1U2U3(self): """Computation as described in R. W. Grosse-Kunstleve, P. D. Adams, J Appl Cryst 2002, 35, 477-480. - Returns: numpy array of eigenvalues of Ucart, first dimension are the atoms in the structure. + + Returns: + np.array: eigenvalues of Ucart. First dimension are the atoms in the structure. """ U1U2U3 = [] for mat in self.thermal_displacement_matrix_cart_matrixform: @@ -434,7 +444,8 @@ 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)). - Returns: Structure object. + Returns: + Structure """ site_properties = {"U11_cif": [], "U22_cif": [], "U33_cif": [], "U23_cif": [], "U13_cif": [], "U12_cif": []} if self.thermal_displacement_matrix_cif is None: @@ -461,8 +472,8 @@ def from_structure_with_site_properties_Ucif(structure: Structure, temperature: properties temperature: temperature for Ucif data - Returns: ThermalDisplacementMatrices Object. - + Returns: + ThermalDisplacementMatrices """ Ucif_matrix = [] # U11, U22, U33, U23, U13, U12 @@ -483,12 +494,13 @@ def from_structure_with_site_properties_Ucif(structure: Structure, temperature: @staticmethod def from_cif_P1(filename: str): """Reads a cif with P1 symmetry including positions and ADPs. - Currently, no check of symmetry is performed as CifParser methods cannot be easily reused - Args: - filename: Filename of the cif. + Currently, no check of symmetry is performed as CifParser methods cannot be easily reused. - Returns: ThermalDisplacementMatrices Object. + Args: + filename: Filename of the CIF. + Returns: + ThermalDisplacementMatrices """ # This code is adapted from the CifParser # to reuse more code from there, the CifParser would need a major refactoring @@ -502,7 +514,7 @@ def from_cif_P1(filename: str): lattice = CifParser.get_lattice_no_exception(data) all_coords = [] - allspecies = [] + all_species = [] for idx in range(len(data["_atom_site_label"])): try: # If site type symbol exists, use it. Otherwise, we use the @@ -513,7 +525,7 @@ def from_cif_P1(filename: str): if not symbol: continue - allspecies.append(symbol) + all_species.append(symbol) x = str2float(data["_atom_site_fract_x"][idx]) y = str2float(data["_atom_site_fract_y"][idx]) z = str2float(data["_atom_site_fract_z"][idx]) @@ -531,7 +543,7 @@ def from_cif_P1(filename: str): ] for idx in range(len(data["_atom_site_aniso_label"])) ] - struct = Structure(lattice, allspecies, all_coords) + struct = Structure(lattice, all_species, all_coords) thermal = ThermalDisplacementMatrices.from_Ucif( thermal_displacement_matrix_cif=thermals_Ucif, structure=struct, temperature=None diff --git a/pymatgen/symmetry/analyzer.py b/pymatgen/symmetry/analyzer.py index dddb0ac4692..52f90d06251 100644 --- a/pymatgen/symmetry/analyzer.py +++ b/pymatgen/symmetry/analyzer.py @@ -35,8 +35,10 @@ if TYPE_CHECKING: from pymatgen.core.periodic_table import Element, Species from pymatgen.core.sites import Site + from pymatgen.symmetry.groups import CrystalSystem logger = logging.getLogger(__name__) +LatticeType = Literal["cubic", "hexagonal", "monoclinic", "orthorhombic", "rhombohedral", "tetragonal", "triclinic"] cite_conventional_cell_algo = due.dcite( Doi("10.1016/j.commatsci.2010.05.010"), @@ -165,9 +167,7 @@ def get_point_group_symbol(self) -> str: return "1" return spglib.get_pointgroup(rotations)[0].strip() - def get_crystal_system( - self, - ) -> Literal["triclinic", "monoclinic", "orthorhombic", "tetragonal", "trigonal", "hexagonal", "cubic"]: + def get_crystal_system(self) -> CrystalSystem: """Get the crystal system for the structure, e.g., (triclinic, orthorhombic, cubic, etc.). @@ -197,9 +197,7 @@ def get_crystal_system( return "hexagonal" return "cubic" - def get_lattice_type( - self, - ) -> Literal["triclinic", "monoclinic", "orthorhombic", "tetragonal", "rhombohedral", "hexagonal", "cubic"]: + def get_lattice_type(self) -> LatticeType: """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. @@ -317,7 +315,7 @@ def get_symmetrized_structure(self): have been grouped into symmetrically equivalent groups. Returns: - :class:`pymatgen.symmetry.structure.SymmetrizedStructure` object. + pymatgen.symmetry.structure.SymmetrizedStructure object. """ ds = self.get_symmetry_dataset() sg = SpacegroupOperations( @@ -1503,7 +1501,7 @@ def iterative_symmetrize(mol, max_n=10, tolerance=0.3, epsilon=1e-2): max_n (int): Maximum number of iterations. tolerance (float): Tolerance for detecting symmetry. Gets passed as Argument into - :class:`~pymatgen.analyzer.symmetry.PointGroupAnalyzer`. + ~pymatgen.analyzer.symmetry.PointGroupAnalyzer. epsilon (float): If the elementwise absolute difference of two subsequently symmetrized structures is smaller epsilon, the iteration stops before ``max_n`` is reached. diff --git a/pymatgen/symmetry/groups.py b/pymatgen/symmetry/groups.py index 0621ea76a71..1e78768be11 100644 --- a/pymatgen/symmetry/groups.py +++ b/pymatgen/symmetry/groups.py @@ -29,6 +29,7 @@ SYMM_DATA = loadfn(os.path.join(os.path.dirname(__file__), "symm_data.json")) +CrystalSystem = Literal["cubic", "hexagonal", "monoclinic", "orthorhombic", "tetragonal", "triclinic", "trigonal"] class SymmetryGroup(Sequence, Stringify, metaclass=ABCMeta): @@ -414,9 +415,7 @@ def check(param, ref, tolerance): return True @property - def crystal_system( - self, - ) -> Literal["cubic", "hexagonal", "trigonal", "tetragonal", "orthorhombic", "monoclinic", "triclinic"]: + def crystal_system(self) -> CrystalSystem: """ Returns: str: Crystal system of the space group, e.g., cubic, hexagonal, etc. diff --git a/pymatgen/symmetry/maggroups.py b/pymatgen/symmetry/maggroups.py index af1dd92f324..65cf5da516e 100644 --- a/pymatgen/symmetry/maggroups.py +++ b/pymatgen/symmetry/maggroups.py @@ -332,7 +332,7 @@ def symmetry_ops(self): """Retrieve magnetic symmetry operations of the space group. Returns: - List of :class:`pymatgen.core.operations.MagSymmOp`. + List of pymatgen.core.operations.MagSymmOp. """ ops = [op_data["op"] for op_data in self._data["bns_operators"]] @@ -361,7 +361,7 @@ def get_orbit(self, p, magmom, tol: float = 1e-5): Args: p: Point as a 3x1 array. - magmom: A magnetic moment, compatible with :class:`pymatgen.electronic_structure.core.Magmom` + magmom: A magnetic moment, compatible with pymatgen.electronic_structure.core.Magmom tol: Tolerance for determining if sites are the same. 1e-5 should be sufficient for most purposes. Set to 0 for exact matching (and also needed for symbolic orbits). diff --git a/pymatgen/transformations/advanced_transformations.py b/pymatgen/transformations/advanced_transformations.py index 6cae4be8cc4..b1900d048f6 100644 --- a/pymatgen/transformations/advanced_transformations.py +++ b/pymatgen/transformations/advanced_transformations.py @@ -637,7 +637,7 @@ def __init__(self, mag_species_spin, order_parameter=0.5, energy_model=None, **k global order parameter and can take values from 0.0 to 1.0 (e.g. 0.5 for antiferromagnetic or 1.0 for ferromagnetic), if list has to be a list of - :class:`pymatgen.transformations.advanced_transformations.MagOrderParameterConstraint` + pymatgen.transformations.advanced_transformations.MagOrderParameterConstraint to specify more complicated orderings, see documentation for MagOrderParameterConstraint more details on usage :param energy_model: Energy model to rank the returned structures, @@ -646,7 +646,7 @@ def __init__(self, mag_species_spin, order_parameter=0.5, energy_model=None, **k structures use SymmetryModel() which ranks structures from most symmetric to least. :param kwargs: Additional kwargs that are passed to - :class:`EnumerateStructureTransformation` such as min_cell_size etc. + EnumerateStructureTransformation such as min_cell_size etc. """ # checking for sensible order_parameter values if isinstance(order_parameter, float): @@ -994,7 +994,7 @@ def __init__( doping sites. This is an inclusionary list. If specified, any sites which are not **kwargs: - Same keyword args as :class:`EnumerateStructureTransformation`, + Same keyword args as EnumerateStructureTransformation, i.e., min_cell_size, etc. """ self.dopant = get_el_sp(dopant) @@ -1320,8 +1320,7 @@ def _partition(collection): def _sort_partitions(partitions_to_sort): """Sort partitions by those we want to check first - (typically, merging two sites into one is the - one to try first). + (typically, merging two sites into one is the one to try first). """ partition_indices = [(idx, [len(p) for p in partition]) for idx, partition in enumerate(partitions_to_sort)] @@ -1681,16 +1680,17 @@ def apply_transformation(self, structure: Structure, return_ranked_list: bool | is returned. If False, only the single lowest energy structure is returned. Defaults to False. - Returns: Slab with adsorbate + Returns: + Slab: with adsorbate """ - sitefinder = AdsorbateSiteFinder( + site_finder = AdsorbateSiteFinder( structure, selective_dynamics=self.selective_dynamics, height=self.height, mi_vec=self.mi_vec, ) - structures = sitefinder.generate_adsorption_structures( + structures = site_finder.generate_adsorption_structures( self.adsorbate, repeat=self.repeat, min_lw=self.min_lw, @@ -1813,7 +1813,7 @@ def __init__( concurrent with the miller index, this enables use with slabs that have been reoriented, but the miller vector must be supplied manually - target_species: List of specific species to substitute + target_species: List of specific species to substitute sub_both_sides (bool): If true, substitute an equivalent site on the other surface range_tol (float): Find viable substitution sites at a specific @@ -1838,16 +1838,17 @@ def apply_transformation(self, structure: Structure, return_ranked_list: bool | is returned. If False, only the single lowest energy structure is returned. Defaults to False. - Returns: Slab with sites substituted + Returns: + list[dict]: each dict has key 'structure' which is a Slab with sites substituted """ - sitefinder = AdsorbateSiteFinder( + site_finder = AdsorbateSiteFinder( structure, selective_dynamics=self.selective_dynamics, height=self.height, mi_vec=self.mi_vec, ) - structures = sitefinder.generate_substitution_structures( + structures = site_finder.generate_substitution_structures( self.atom, target_species=self.target_species, sub_both_sides=self.sub_both_sides, @@ -1939,7 +1940,8 @@ def __init__( @staticmethod def _get_max_neighbor_distance(struct, shell): - """Calculate maximum nearest neighbor distance + """Calculate maximum nearest neighbor distance. + Args: struct: pymatgen Structure object shell: nearest neighbor shell, such that shell=1 is the first nearest @@ -1962,7 +1964,8 @@ def _get_max_neighbor_distance(struct, shell): @staticmethod def _get_disordered_substructure(struc_disordered): - """Converts disordered structure into a substructure consisting of only disordered sites + """Converts disordered structure into a substructure consisting of only disordered sites. + Args: struc_disordered: pymatgen disordered Structure object. @@ -1978,7 +1981,8 @@ def _get_disordered_substructure(struc_disordered): @staticmethod def _sqs_cluster_estimate(struc_disordered, cluster_size_and_shell: dict[int, int] | None = None): - """Set up an ATAT cluster.out file for a given structure and set of constraints + """Set up an ATAT cluster.out file for a given structure and set of constraints. + Args: struc_disordered: disordered pymatgen Structure object cluster_size_and_shell: dict of integers {cluster: shell}. @@ -2048,7 +2052,8 @@ def apply_transformation(self, structure: Structure, return_ranked_list: bool | @staticmethod def _get_unique_bestsqs_strucs(sqs, best_only, return_ranked_list, remove_duplicate_structures, reduction_algo): """Gets unique sqs structures with lowest objective function. Requires an mcsqs output that has been run - in parallel, otherwise returns Sqs.bestsqs + in parallel, otherwise returns Sqs.bestsqs. + Args: sqs (Sqs): Sqs class object. best_only (bool): only return structures with lowest objective function. diff --git a/pymatgen/transformations/standard_transformations.py b/pymatgen/transformations/standard_transformations.py index 687fbf1e44c..037fdf17700 100644 --- a/pymatgen/transformations/standard_transformations.py +++ b/pymatgen/transformations/standard_transformations.py @@ -403,7 +403,7 @@ class PartialRemoveSpecieTransformation(AbstractTransformation): Given that the solution to selecting the right removals is NP-hard, there are several algorithms provided with varying degrees of accuracy and speed. Please see - :class:`pymatgen.transformations.site_transformations.PartialRemoveSitesTransformation`. + pymatgen.transformations.site_transformations.PartialRemoveSitesTransformation. """ ALGO_FAST = 0 diff --git a/pymatgen/util/coord.py b/pymatgen/util/coord.py index 8a4a5903739..0cc29d96365 100644 --- a/pymatgen/util/coord.py +++ b/pymatgen/util/coord.py @@ -413,9 +413,12 @@ def in_simplex(self, point, tolerance=1e-8): return (self.bary_coords(point) >= -tolerance).all() def line_intersection(self, point1, point2, tolerance=1e-8): - """Computes the intersection points of a line with a simplex + """Computes the intersection points of a line with a simplex. + Args: - point1, point2 ([float]): Points that determine the line. + point1 (Sequence[float]): 1st point to determine the line. + point2 (Sequence[float]): 2nd point to determine the line. + tolerance (float): Tolerance for checking if an intersection is in the simplex. Defaults to 1e-8. Returns: points where the line intersects the simplex (0, 1, or 2). diff --git a/pymatgen/util/plotting.py b/pymatgen/util/plotting.py index 839a47a149f..c87d52aa78b 100644 --- a/pymatgen/util/plotting.py +++ b/pymatgen/util/plotting.py @@ -3,7 +3,7 @@ from __future__ import annotations import math -from typing import Literal +from typing import TYPE_CHECKING, Literal import matplotlib.pyplot as plt import numpy as np @@ -11,6 +11,9 @@ from pymatgen.core.periodic_table import Element +if TYPE_CHECKING: + from mpl_toolkits.mplot3d.axes3d import Axes3D + def pretty_plot( width: float = 8, @@ -534,7 +537,7 @@ def van_arkel_triangle(list_of_materials, annotate=True): return plt -def get_ax_fig_plt(ax: plt.Axes = None, **kwargs): +def get_ax_fig(ax: plt.Axes = None, **kwargs) -> tuple[plt.Axes, plt.Figure]: """Helper function used in plot functions supporting an optional Axes argument. If ax is None, we build the `matplotlib` figure and create the Axes else we return the current active figure. @@ -544,22 +547,18 @@ def get_ax_fig_plt(ax: plt.Axes = None, **kwargs): kwargs: keyword arguments are passed to plt.figure if ax is not None. Returns: - ax: :class:`Axes` object - figure: matplotlib figure - plt: matplotlib pyplot module. + tuple[plt.Axes, plt.Figure]: matplotlib Axes object and Figure objects """ - import matplotlib.pyplot as plt - if ax is None: fig = plt.figure(**kwargs) ax = fig.gca() else: fig = plt.gcf() - return ax, fig, plt + return ax, fig -def get_ax3d_fig_plt(ax: plt.Axes = None, **kwargs): +def get_ax3d_fig(ax: plt.Axes = None, **kwargs) -> tuple[Axes3D, plt.Figure]: """Helper function used in plot functions supporting an optional Axes3D argument. If ax is None, we build the `matplotlib` figure and create the Axes3D else we return the current active figure. @@ -569,20 +568,17 @@ def get_ax3d_fig_plt(ax: plt.Axes = None, **kwargs): kwargs: keyword arguments are passed to plt.figure if ax is not None. Returns: - ax: :class:`Axes` object - figure: matplotlib figure - plt: matplotlib pyplot module. + tuple[Axes3D, Figure]: matplotlib Axes3D and corresponding figure objects """ - import matplotlib.pyplot as plt - from mpl_toolkits.mplot3d import axes3d + from mpl_toolkits.mplot3d.axes3d import Axes3D if ax is None: fig = plt.figure(**kwargs) - ax = axes3d.Axes3D(fig) + ax = Axes3D(fig) else: fig = plt.gcf() - return ax, fig, plt + return ax, fig def get_axarray_fig_plt( @@ -594,7 +590,7 @@ def get_axarray_fig_plt( current active figure. Returns: - ax: Array of :class:`Axes` objects + ax: Array of Axes objects figure: matplotlib figure plt: matplotlib pyplot module. """ diff --git a/tasks.py b/tasks.py index d765e5d5ab1..008837df9d2 100644 --- a/tasks.py +++ b/tasks.py @@ -68,8 +68,7 @@ def make_doc(ctx): @task def make_dash(ctx): - """ - Make customized doc version for Dash. + """Make customized doc version for Dash. :param ctx: """