Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Doc string standardization #3805

Merged
merged 6 commits into from
May 3, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
imperative method doc strings
  • Loading branch information
janosh committed May 2, 2024
commit 5f01e46b724acccbfd7a4c3f75c0ab96f75612ce
2 changes: 1 addition & 1 deletion dev_scripts/potcar_scrambler.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ def generate_fake_potcar_libraries() -> None:


def potcar_cleanser() -> None:
"""Function to replace copyrighted POTCARs used in io.vasp.sets testing
"""Replace copyrighted POTCARs used in io.vasp.sets testing
with dummy POTCARs that have scrambled PSP and kinetic energy values
(but retain the original header information which is also found in OUTCARs
and freely shared by VASP)
Expand Down
58 changes: 10 additions & 48 deletions pymatgen/alchemy/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,23 +19,20 @@


class AbstractStructureFilter(MSONable, abc.ABC):
"""AbstractStructureFilter that defines an API to perform testing of
Structures. Structures that return True to a test are retained during
transmutation while those that return False are removed.
"""Structures that return True when passed to the test() method are retained during
transmutation. Those that return False are removed.
"""

@abc.abstractmethod
def test(self, structure: Structure):
"""Method to execute the test.
"""Structures that return true are kept in the Transmuter object during filtering.

Args:
structure (Structure): Input structure to test

Returns:
bool: Structures that return true are kept in the Transmuter
object during filtering.
bool: True if structure passes filter.
"""
return


class ContainsSpecieFilter(AbstractStructureFilter):
Expand All @@ -59,11 +56,7 @@ def __init__(self, species, strict_compare=False, AND=True, exclude=False):
self._exclude = exclude

def test(self, structure: Structure):
"""Method to execute the test.

Returns:
bool: True if structure does not contain specified species.
"""
"""True if structure does not contain specified species."""
# set up lists to compare
if not self._strict:
# compare by atomic number
Expand Down Expand Up @@ -120,9 +113,7 @@ def from_dict(cls, dct: dict) -> Self:


class SpecieProximityFilter(AbstractStructureFilter):
"""This filter removes structures that have certain species that are too close
together.
"""
"""This filter removes structures that have certain species that are too close together."""

def __init__(self, specie_and_min_dist_dict):
"""
Expand All @@ -137,14 +128,7 @@ def __init__(self, specie_and_min_dist_dict):
self.specie_and_min_dist = {get_el_sp(k): v for k, v in specie_and_min_dist_dict.items()}

def test(self, structure: Structure):
"""Method to execute the test.

Args:
structure (Structure): Input structure to test

Returns:
bool: True if structure does not contain species within specified distances.
"""
"""True if structure does not contain species within specified distances."""
all_species = set(self.specie_and_min_dist)
for site in structure:
species = set(site.species)
Expand Down Expand Up @@ -252,14 +236,7 @@ def __init__(self, existing_structures, structure_matcher=None, symprec=None):
self.structure_matcher = structure_matcher or StructureMatcher(comparator=ElementComparator())

def test(self, structure: Structure):
"""Method to execute the test.

Args:
structure (Structure): Input structure to test

Returns:
bool: True if structure is not in existing list.
"""
"""True if structure is not in existing list."""

def get_sg(s):
finder = SpacegroupAnalyzer(s, symprec=self.symprec)
Expand Down Expand Up @@ -299,14 +276,7 @@ def __init__(self):
"""No args required."""

def test(self, structure: Structure):
"""Method to execute the test.

Args:
structure (Structure): Input structure to test

Returns:
bool: True if structure is neutral.
"""
"""True if structure is neutral."""
return structure.charge == 0.0


Expand All @@ -332,15 +302,7 @@ def __init__(self, sp1, sp2, max_dist):
self.max_dist = max_dist

def test(self, structure: Structure):
"""Method to execute the test.

Args:
structure (Structure): Input structure to test

Returns:
bool: True if structure does not contain the two species are distances
greater than max_dist.
"""
"""True if structure contains the two species but their distance is 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]
frac_coords1 = structure.frac_coords[sp1_indices, :]
Expand Down
8 changes: 3 additions & 5 deletions pymatgen/alchemy/transmuters.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,13 +187,11 @@ def add_tags(self, tags):
self.set_parameter("tags", tags)

def append_transformed_structures(self, trafo_structs_or_transmuter):
"""Method is overloaded to accept either a list of transformed structures
or transmuter, it which case it appends the second transmuter"s
structures.
"""Overloaded to accept either a list of transformed structures
or transmuter, it which case it appends the second transmuter's structures.

Args:
trafo_structs_or_transmuter: A list of transformed structures or a
transmuter.
trafo_structs_or_transmuter: A list of transformed structures or a transmuter.
"""
if isinstance(trafo_structs_or_transmuter, self.__class__):
self.transformed_structures += trafo_structs_or_transmuter.transformed_structures
Expand Down
9 changes: 4 additions & 5 deletions pymatgen/analysis/adsorption.py
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,7 @@ def generate_adsorption_structures(
reorient=True,
find_args=None,
):
"""Function that generates all adsorption structures for a given
"""Generate all adsorption structures for a given
molecular adsorbate. Can take repeat argument or minimum length/width
of precursor slab as an input.

Expand Down Expand Up @@ -473,7 +473,7 @@ def adsorb_both_surfaces(
reorient=True,
find_args=None,
):
"""Function that generates all adsorption structures for a given
"""Generate all adsorption structures for a given
molecular adsorbate on both surfaces of a slab. This is useful for
calculating surface energy where both surfaces need to be equivalent or
if we want to calculate nonpolar systems.
Expand Down Expand Up @@ -535,7 +535,7 @@ def generate_substitution_structures(
range_tol=1e-2,
dist_from_surf=0,
):
"""Function that performs substitution-type doping on the surface and
"""Perform substitution-type doping on the surface and
returns all possible configurations where one dopant is substituted per
surface. Can substitute one surface or both.

Expand Down Expand Up @@ -644,8 +644,7 @@ def plot_slab(
adsorption_sites=True,
inverse=False,
):
"""Function that helps visualize the slab in a 2-D plot, for convenient
viewing of output of AdsorbateSiteFinder.
"""Help visualize the slab in a 2-D plot, for convenient viewing of output of AdsorbateSiteFinder.

Args:
slab (slab): Slab object to be visualized
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/analysis/fragmenter.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,8 +295,8 @@ def _open_all_rings(self) -> None:


def open_ring(mol_graph: MoleculeGraph, bond: list, opt_steps: int) -> MoleculeGraph:
"""Function to actually open a ring using OpenBabel's local opt. Given a molecule
graph and a bond, convert the molecule graph into an OpenBabel molecule, remove
"""Open a ring using OpenBabel's local opt. Given a molecule graph and a bond,
convert the molecule graph into an OpenBabel molecule, remove
the given bond, perform the local opt with the number of steps determined by
self.steps, and then convert the resulting structure back into a molecule graph
to be returned.
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/analysis/local_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -4396,7 +4396,7 @@ def metal_edge_extender(
metals: list | tuple | None = ("Li", "Mg", "Ca", "Zn", "B", "Al"),
coordinators: list | tuple = ("O", "N", "F", "S", "Cl"),
):
"""Function to identify and add missed coordinate bond edges for metals.
"""Identify and add missed coordinate bond edges for metals.

Args:
mol_graph: pymatgen.analysis.graphs.MoleculeGraph object
Expand Down
9 changes: 3 additions & 6 deletions pymatgen/analysis/phase_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -2958,15 +2958,12 @@ def _create_plotly_markers(self, highlight_entries=None, label_uncertainties=Fal
Creates stable and unstable marker plots for overlaying on the phase diagram.

Returns:
Tuple of Plotly go.Scatter (unary, binary), go.Scatterternary(ternary_2d),
or go.Scatter3d (ternary_3d, quaternary) objects in order:
(stable markers, unstable markers)
tuple[go.Scatter]: Plotly Scatter objects (unary, binary), go.Scatterternary(ternary_2d),
or go.Scatter3d (ternary_3d, quaternary) objects in order: (stable markers, unstable markers)
"""

def get_marker_props(coords, entries):
"""Method for getting marker locations, hovertext, and error bars
from pd_plot_data.
"""
"""Get marker locations, hovertext, and error bars from pd_plot_data."""
x, y, z, texts, energies, uncertainties = [], [], [], [], [], []

is_stable = [entry in self._pd.stable_entries for entry in entries]
Expand Down
6 changes: 3 additions & 3 deletions pymatgen/core/lattice.py
Original file line number Diff line number Diff line change
Expand Up @@ -1306,7 +1306,7 @@ def get_points_in_sphere(
(parallelepiped) which would contain a sphere of radius r. for this
we need the projection of a_1 on a unit vector perpendicular
to a_2 & a_3 (i.e. the unit vector in the direction b_1) to
determine how many a_1"s it will take to contain the sphere.
determine how many a_1's it will take to contain the sphere.

Nxmax = r * length_of_b_1 / (2 Pi)

Expand Down Expand Up @@ -1366,7 +1366,7 @@ def get_points_in_sphere_py(
(parallelepiped) which would contain a sphere of radius r. for this
we need the projection of a_1 on a unit vector perpendicular
to a_2 & a_3 (i.e. the unit vector in the direction b_1) to
determine how many a_1"s it will take to contain the sphere.
determine how many a_1's it will take to contain the sphere.

Nxmax = r * length_of_b_1 / (2 Pi)

Expand Down Expand Up @@ -1423,7 +1423,7 @@ def get_points_in_sphere_old(
(parallelepiped) which would contain a sphere of radius r. for this
we need the projection of a_1 on a unit vector perpendicular
to a_2 & a_3 (i.e. the unit vector in the direction b_1) to
determine how many a_1"s it will take to contain the sphere.
determine how many a_1's it will take to contain the sphere.

Nxmax = r * length_of_b_1 / (2 Pi)

Expand Down
7 changes: 3 additions & 4 deletions pymatgen/core/structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -1509,16 +1509,15 @@ def get_sites_in_sphere(
include_image: bool = False,
) -> list[PeriodicNeighbor]:
"""Find all sites within a sphere from the point, including a site (if any)
sitting on the point itself. This includes sites in other periodic
images.
sitting on the point itself. This includes sites in other periodic images.

Algorithm:

1. place sphere of radius r in crystal and determine minimum supercell
(parallelepiped) which would contain a sphere of radius r. for this
we need the projection of a_1 on a unit vector perpendicular
to a_2 & a_3 (i.e. the unit vector in the direction b_1) to
determine how many a_1"s it will take to contain the sphere.
determine how many a_1's it will take to contain the sphere.

Nxmax = r * length_of_b_1 / (2 Pi)

Expand Down Expand Up @@ -4506,7 +4505,7 @@ def calculate(self, calculator: str | Calculator = "m3gnet", verbose: bool = Fal

@classmethod
def from_prototype(cls, prototype: str, species: Sequence, **kwargs) -> Self:
"""Method to rapidly construct common prototype structures.
"""Rapidly construct common prototype structures.

Args:
prototype: Name of prototype. e.g. cubic, rocksalt, perovksite etc.
Expand Down
11 changes: 5 additions & 6 deletions pymatgen/core/tensors.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,12 +158,11 @@ def project(self, n):
float: scalar value corresponding to the projection of
the tensor into the vector
"""
n = get_uvec(n)
return self.einsum_sequence([n] * self.rank)
unit_vec = get_uvec(n)
return self.einsum_sequence([unit_vec] * self.rank)

def average_over_unit_sphere(self, quad=None):
"""Method for averaging the tensor projection over the unit
with option for custom quadrature.
"""Average the tensor projection over the unit with option for custom quadrature.

Args:
quad (dict): quadrature for integration, should be
Expand Down Expand Up @@ -952,7 +951,7 @@ def polar_decomposition(self, side="right"):
return polar(self, side=side)


def get_uvec(vec):
def get_uvec(vec: np.ndarray) -> np.ndarray:
"""Get a unit vector parallel to input vector."""
norm = np.linalg.norm(vec)
if norm < 1e-8:
Expand All @@ -961,7 +960,7 @@ def get_uvec(vec):


def symmetry_reduce(tensors, structure: Structure, tol: float = 1e-8, **kwargs):
"""Function that converts a list of tensors corresponding to a structure
"""Convert a list of tensors corresponding to a structure
and returns a dictionary consisting of unique tensor keys with SymmOp
values corresponding to transformations that will result in derivative
tensors from the original list.
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/core/units.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,7 @@ def __neg__(self):
return FloatWithUnit(super().__neg__(), unit_type=self._unit_type, unit=self._unit)

def __getnewargs__(self):
"""Function used by pickle to recreate object."""
"""Used by pickle to recreate object."""
# TODO There's a problem with _unit_type if we try to unpickle objects from file.
# since self._unit_type might not be defined. I think this is due to
# the use of decorators (property and unitized). In particular I have problems with "amu"
Expand Down
11 changes: 5 additions & 6 deletions pymatgen/electronic_structure/bandstructure.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ def __init__(
self.is_spin_polarized = len(self.bands) == 2

def get_projection_on_elements(self):
"""Method returning a dictionary of projections on elements.
"""Get a dictionary of projections on elements.

Returns:
a dictionary in the {Spin.up:[][{Element: [values]}],
Expand All @@ -254,7 +254,7 @@ def get_projection_on_elements(self):
return result

def get_projections_on_elements_and_orbitals(self, el_orb_spec: dict[str, list[str]]):
"""Method returning a dictionary of projections on elements and specific orbitals.
"""Get a dictionary of projections on elements and specific orbitals.

Args:
el_orb_spec (dict[str, list[str]]): A dictionary of elements and orbitals which
Expand Down Expand Up @@ -1005,8 +1005,8 @@ def from_old_dict(cls, dct) -> Self:
)

def get_projection_on_elements(self):
"""Method returning a dictionary of projections on elements.
It sums over all available orbitals for each element.
"""Get a dictionary of projections on elements. It sums over all available orbitals
for each element.

Returns:
a dictionary in the {Spin.up:[][{Element:values}],
Expand All @@ -1025,8 +1025,7 @@ def get_projection_on_elements(self):
return result

def get_projections_on_elements_and_orbitals(self, el_orb_spec):
"""Method returning a dictionary of projections on elements and specific
orbitals.
"""Return a dictionary of projections on elements and specific orbitals.

Args:
el_orb_spec: A dictionary of Elements and Orbitals for which we want
Expand Down
15 changes: 7 additions & 8 deletions pymatgen/electronic_structure/boltztrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -844,14 +844,13 @@ def __init__(
self.fermi_surface_data = fermi_surface_data

def get_symm_bands(self, structure: Structure, efermi, kpt_line=None, labels_dict=None):
"""Function useful to read bands from Boltztrap output and get a
BandStructureSymmLine object comparable with that one from a DFT
calculation (if the same kpt_line is provided). Default kpt_line
and labels_dict is the standard path of high symmetry k-point for
the specified structure. They could be extracted from the
BandStructureSymmLine object that you want to compare with. efermi
variable must be specified to create the BandStructureSymmLine
object (usually it comes from DFT or Boltztrap calc).
"""Useful to read bands from Boltztrap output and get a BandStructureSymmLine object
comparable with that one from a DFT calculation (if the same kpt_line is
provided). Default kpt_line and labels_dict is the standard path of high symmetry
k-point for the specified structure. They could be extracted from the
BandStructureSymmLine object that you want to compare with. efermi variable must
be specified to create the BandStructureSymmLine object (usually it comes from DFT
or Boltztrap calc).
"""
try:
if kpt_line is None:
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/electronic_structure/boltztrap2.py
Original file line number Diff line number Diff line change
Expand Up @@ -979,7 +979,7 @@ def plot_props(
xlim=(-2, 2),
ax: plt.Axes = None,
):
"""Function to plot the transport properties.
"""Plot the transport properties.

Args:
prop_y: property to plot among ("Conductivity","Seebeck","Kappa","Carrier_conc",
Expand Down
Loading