Skip to content

Commit

Permalink
Format doc strings (#3790)
Browse files Browse the repository at this point in the history
* doc string no line break after """\n\s+Get

* """\n\s+Set -> """Set

* remove __deepcopy__ from io/cp2k/inputs.py Section and SectionList

* """\n\s+E -> """E

* """\n\s+F -> """F

* imperative form: finds->find, initializes->initialize, ...

* return if ...: return True; return False -> return ...

* deprecate NRANDOM kwarg of coordination_geometry_symmetry_measures_fallback_random

snake_case symmop->symm_op

* imperative form: Gives->Get, Shows->Show, ...

* fix mypy

* "Class for ..." -> "..."
  • Loading branch information
janosh authored Apr 28, 2024
1 parent c9292ed commit 9964c4a
Show file tree
Hide file tree
Showing 153 changed files with 709 additions and 1,062 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,7 @@ def __init__(self, initial_environment_symbol, expected_final_environment_symbol

@classmethod
def simple_expansion(cls, initial_environment_symbol, expected_final_environment_symbol, neighbors_indices):
"""
Simple expansion of a coordination environment.
"""Simple expansion of a coordination environment.
Args:
initial_environment_symbol (str): The initial coordination environment symbol.
Expand Down
9 changes: 3 additions & 6 deletions dev_scripts/potcar_scrambler.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,7 @@ def _read_fortran_str_and_scramble(self, input_str: str, bloat: float = 1.5):
return input_str

def scramble_single_potcar(self, potcar: PotcarSingle) -> str:
"""
Scramble the body of a POTCAR, retain the PSCTR header information.
"""Scramble the body of a POTCAR, retain the PSCTR header information.
To the best of my (ADK) knowledge, in the OUTCAR file,
almost all information from the POTCAR in the "PSCTR" block
Expand All @@ -84,8 +83,7 @@ def scramble_single_potcar(self, potcar: PotcarSingle) -> str:
is included. This information is not scrambled below.
"""
scrambled_potcar_str = ""
needs_sha256 = False
scramble_values = False
needs_sha256 = scramble_values = False
og_sha_str = "SHA256 = None\n"
for line in potcar.data.split("\n")[:-1]:
single_line_rows = line.split(";")
Expand Down Expand Up @@ -174,8 +172,7 @@ def generate_fake_potcar_libraries() -> None:


def potcar_cleanser() -> None:
"""
Function to replace copyrighted POTCARs used in io.vasp.sets testing
"""Function to 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
18 changes: 9 additions & 9 deletions pymatgen/alchemy/materials.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def __init__(
history: list[AbstractTransformation | dict[str, Any]] | None = None,
other_parameters: dict[str, Any] | None = None,
) -> None:
"""Initializes a transformed structure from a structure.
"""Initialize a transformed structure from a structure.
Args:
structure (Structure): Input structure
Expand Down Expand Up @@ -102,7 +102,7 @@ def __len__(self) -> int:
def append_transformation(
self, transformation, return_alternatives: bool = False, clear_redo: bool = True
) -> list[TransformedStructure] | None:
"""Appends a transformation to the TransformedStructure.
"""Append a transformation to the TransformedStructure.
Args:
transformation: Transformation to append
Expand Down Expand Up @@ -157,7 +157,7 @@ def append_transformation(
return None

def append_filter(self, structure_filter: AbstractStructureFilter) -> None:
"""Adds a filter.
"""Add a filter.
Args:
structure_filter (StructureFilter): A filter implementing the
Expand All @@ -172,7 +172,7 @@ def extend_transformations(
transformations: list[AbstractTransformation],
return_alternatives: bool = False,
) -> None:
"""Extends a sequence of transformations to the TransformedStructure.
"""Extend a sequence of transformations to the TransformedStructure.
Args:
transformations: Sequence of Transformations
Expand Down Expand Up @@ -203,7 +203,7 @@ def write_vasp_input(
create_directory: bool = True,
**kwargs,
) -> None:
"""Writes VASP input to an output_dir.
"""Write VASP input to an output_dir.
Args:
vasp_input_set: pymatgen.io.vasp.sets.VaspInputSet like object that creates vasp input files from
Expand Down Expand Up @@ -232,7 +232,7 @@ def __str__(self) -> str:
return "\n".join(output)

def set_parameter(self, key: str, value: Any) -> TransformedStructure:
"""Sets a parameter.
"""Set a parameter.
Args:
key (str): The string key.
Expand Down Expand Up @@ -270,7 +270,7 @@ def from_cif_str(
primitive: bool = True,
occupancy_tolerance: float = 1.0,
) -> Self:
"""Generates TransformedStructure from a cif string.
"""Generate TransformedStructure from a cif string.
Args:
cif_string (str): Input cif string. Should contain only one
Expand Down Expand Up @@ -314,7 +314,7 @@ def from_poscar_str(
poscar_string: str,
transformations: list[AbstractTransformation] | None = None,
) -> Self:
"""Generates TransformedStructure from a poscar string.
"""Generate TransformedStructure from a poscar string.
Args:
poscar_string (str): Input POSCAR string.
Expand Down Expand Up @@ -347,7 +347,7 @@ def as_dict(self) -> dict[str, Any]:

@classmethod
def from_dict(cls, dct: dict) -> Self:
"""Creates a TransformedStructure from a dict."""
"""Create a TransformedStructure from a dict."""
struct = Structure.from_dict(dct)
return cls(struct, history=dct["history"], other_parameters=dct.get("other_parameters"))

Expand Down
16 changes: 8 additions & 8 deletions pymatgen/alchemy/transmuters.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def __init__(
extend_collection: int = 0,
ncores: int | None = None,
) -> None:
"""Initializes a transmuter from an initial list of
"""Initialize a transmuter from an initial list of
pymatgen.alchemy.materials.TransformedStructure.
Args:
Expand Down Expand Up @@ -101,7 +101,7 @@ def redo_next_change(self) -> None:
x.redo_next_change()

def append_transformation(self, transformation, extend_collection=False, clear_redo=True):
"""Appends a transformation to all TransformedStructures.
"""Append a transformation to all TransformedStructures.
Args:
transformation: Transformation to append
Expand Down Expand Up @@ -134,7 +134,7 @@ def append_transformation(self, transformation, extend_collection=False, clear_r
self.transformed_structures.extend(new_structures)

def extend_transformations(self, transformations):
"""Extends a sequence of transformations to the TransformedStructure.
"""Extend a sequence of transformations to the TransformedStructure.
Args:
transformations: Sequence of Transformations
Expand All @@ -143,7 +143,7 @@ def extend_transformations(self, transformations):
self.append_transformation(trafo)

def apply_filter(self, structure_filter):
"""Applies a structure_filter to the list of TransformedStructures
"""Apply a structure_filter to the list of TransformedStructures
in the transmuter.
Args:
Expand Down Expand Up @@ -224,12 +224,12 @@ def from_structures(cls, structures, transformations=None, extend_collection=0)


class CifTransmuter(StandardTransmuter):
"""Generates a Transmuter from a cif string, possibly containing multiple
"""Generate a Transmuter from a cif string, possibly containing multiple
structures.
"""

def __init__(self, cif_string, transformations=None, primitive=True, extend_collection=False):
"""Generates a Transmuter from a cif string, possibly
"""Generate a Transmuter from a cif string, possibly
containing multiple structures.
Args:
Expand Down Expand Up @@ -259,7 +259,7 @@ def __init__(self, cif_string, transformations=None, primitive=True, extend_coll

@classmethod
def from_filenames(cls, filenames, transformations=None, primitive=True, extend_collection=False) -> Self:
"""Generates a TransformedStructureCollection from a cif, possibly
"""Generate a TransformedStructureCollection from a cif, possibly
containing multiple structures.
Args:
Expand All @@ -282,7 +282,7 @@ def from_filenames(cls, filenames, transformations=None, primitive=True, extend_


class PoscarTransmuter(StandardTransmuter):
"""Generates a transmuter from a sequence of POSCARs."""
"""Generate a transmuter from a sequence of POSCARs."""

def __init__(self, poscar_string, transformations=None, extend_collection=False):
"""
Expand Down
29 changes: 13 additions & 16 deletions pymatgen/analysis/adsorption.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ def from_bulk_and_miller(
selective_dynamics=False,
undercoord_threshold=0.09,
) -> Self:
"""This method constructs the adsorbate site finder from a bulk
"""Construct the adsorbate site finder from a bulk
structure and a miller index, which allows the surface sites to be
determined from the difference in bulk and slab coordination, as
opposed to the height threshold.
Expand Down Expand Up @@ -150,15 +150,12 @@ def from_bulk_and_miller(
surf_props += ["surface"]
else:
surf_props += ["subsurface"]
new_site_properties = {
"surface_properties": surf_props,
"undercoords": under_coords,
}
new_site_properties = {"surface_properties": surf_props, "undercoords": under_coords}
new_slab = this_slab.copy(site_properties=new_site_properties)
return cls(new_slab, selective_dynamics)

def find_surface_sites_by_height(self, slab: Slab, height=0.9, xy_tol=0.05):
"""This method finds surface sites by determining which sites are
"""Find surface sites by determining which sites are
within a threshold value in height from the topmost site in a list of
sites.
Expand Down Expand Up @@ -196,7 +193,7 @@ def find_surface_sites_by_height(self, slab: Slab, height=0.9, xy_tol=0.05):
return surf_sites

def assign_site_properties(self, slab: Slab, height=0.9):
"""Assigns site properties."""
"""Assign site properties."""
if "surface_properties" in slab.site_properties:
return slab

Expand All @@ -205,7 +202,7 @@ def assign_site_properties(self, slab: Slab, height=0.9):
return slab.copy(site_properties={"surface_properties": surf_props})

def get_extended_surface_mesh(self, repeat=(5, 5, 1)):
"""Gets an extended surface mesh for to use for adsorption site finding
"""Get an extended surface mesh for to use for adsorption site finding
by constructing supercell of surface sites.
Args:
Expand Down Expand Up @@ -233,7 +230,7 @@ def find_adsorption_sites(
positions=("ontop", "bridge", "hollow"),
no_obtuse_hollow=True,
):
"""Finds surface sites according to the above algorithm. Returns a list
"""Find surface sites according to the above algorithm. Returns a list
of corresponding Cartesian coordinates.
Args:
Expand Down Expand Up @@ -307,7 +304,7 @@ def find_adsorption_sites(
return ads_sites

def symm_reduce(self, coords_set, threshold=1e-6):
"""Reduces the set of adsorbate sites by finding removing symmetrically
"""Reduce the set of adsorbate sites by finding removing symmetrically
equivalent duplicates.
Args:
Expand All @@ -332,7 +329,7 @@ def symm_reduce(self, coords_set, threshold=1e-6):
return [self.slab.lattice.get_cartesian_coords(coords) for coords in unique_coords]

def near_reduce(self, coords_set, threshold=1e-4):
"""Prunes coordinate set for coordinates that are within threshold.
"""Prune coordinate set for coordinates that are within threshold.
Args:
coords_set (Nx3 array-like): list or array of coordinates
Expand All @@ -347,7 +344,7 @@ def near_reduce(self, coords_set, threshold=1e-4):

@classmethod
def ensemble_center(cls, site_list, indices, cartesian=True):
"""Finds the center of an ensemble of sites selected from a list of
"""Find the center of an ensemble of sites selected from a list of
sites. Helper method for the find_adsorption_sites algorithm.
Args:
Expand All @@ -363,7 +360,7 @@ def ensemble_center(cls, site_list, indices, cartesian=True):
return np.average([site_list[idx].frac_coords for idx in indices], axis=0)

def add_adsorbate(self, molecule: Molecule, ads_coord, repeat=None, translate=True, reorient=True):
"""Adds an adsorbate at a particular coordinate. Adsorbate represented
"""Add an adsorbate at a particular coordinate. Adsorbate represented
by a Molecule object and is translated to (0, 0, 0) if translate is
True, or positioned relative to the input adsorbate coordinate if
translate is False.
Expand Down Expand Up @@ -604,7 +601,7 @@ def get_mi_vec(slab):


def get_rot(slab: Slab) -> SymmOp:
"""Gets the transformation to rotate the z axis into the miller index."""
"""Get the transformation to rotate the z axis into the miller index."""
new_z = get_mi_vec(slab)
a, _b, _c = slab.lattice.matrix
new_x = a / np.linalg.norm(a)
Expand All @@ -616,13 +613,13 @@ def get_rot(slab: Slab) -> SymmOp:


def put_coord_inside(lattice, cart_coordinate):
"""Converts a Cartesian coordinate such that it is inside the unit cell."""
"""Convert a Cartesian coordinate such that it is inside the unit cell."""
fc = lattice.get_fractional_coords(cart_coordinate)
return lattice.get_cartesian_coords([c - np.floor(c) for c in fc])


def reorient_z(structure):
"""Reorients a structure such that the z axis is concurrent with the normal
"""Reorient a structure such that the z axis is concurrent with the normal
to the A-B plane.
"""
struct = structure.copy()
Expand Down
14 changes: 6 additions & 8 deletions pymatgen/analysis/bond_dissociation.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import logging
import warnings
from typing import cast

import networkx as nx
from monty.json import MSONable
Expand Down Expand Up @@ -74,7 +75,8 @@ def __init__(
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]
final_mol = cast(dict, molecule_entry["final_molecule"])
final_charge = int(final_mol["charge"]) # type: ignore[index]
if not allow_additional_charge_separation:
if final_charge == 0:
self.expected_charges = [-1, 0, 1]
Expand All @@ -90,9 +92,7 @@ def __init__(
self.expected_charges = [final_charge - 2, final_charge - 1, final_charge, final_charge + 1]

# Build principle molecule graph
self.mol_graph = MoleculeGraph.from_local_env_strategy(
Molecule.from_dict(molecule_entry["final_molecule"]), OpenBabelNN()
)
self.mol_graph = MoleculeGraph.from_local_env_strategy(Molecule.from_dict(final_mol), OpenBabelNN())
# Loop through bonds, aka graph edges, and fragment and process:
for bond in self.mol_graph.graph.edges:
bonds = [(bond[0], bond[1])]
Expand Down Expand Up @@ -245,8 +245,7 @@ def fragment_and_process(self, bonds):
n_entries_for_this_frag_pair += 1

def search_fragment_entries(self, frag) -> list:
"""
Search all fragment entries for those isomorphic to the given fragment.
"""Search all fragment entries for those isomorphic to the given fragment.
We distinguish between entries where both initial and final MoleculeGraphs are isomorphic to the
given fragment (entries) vs those where only the initial MoleculeGraph is isomorphic to the given
fragment (initial_entries) vs those where only the final MoleculeGraph is isomorphic (final_entries).
Expand All @@ -267,8 +266,7 @@ def search_fragment_entries(self, frag) -> list:
return [entries, initial_entries, final_entries]

def filter_fragment_entries(self, fragment_entries: list) -> None:
"""
Filter the fragment entries.
"""Filter the fragment entries.
Args:
fragment_entries (List): Fragment entries to be filtered.
Expand Down
7 changes: 3 additions & 4 deletions pymatgen/analysis/bond_valence.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@


def calculate_bv_sum(site, nn_list, scale_factor=1.0):
"""Calculates the BV sum of a site.
"""Calculate the BV sum of a site.
Args:
site (PeriodicSite): The central site to calculate the bond valence
Expand All @@ -62,7 +62,7 @@ def calculate_bv_sum(site, nn_list, scale_factor=1.0):


def calculate_bv_sum_unordered(site, nn_list, scale_factor=1):
"""Calculates the BV sum of a site for unordered structures.
"""Calculate the BV sum of a site for unordered structures.
Args:
site (PeriodicSite): The central site to calculate the bond valence
Expand Down Expand Up @@ -424,8 +424,7 @@ def _recurse(assigned=None):
raise ValueError("Valences cannot be assigned!")

def get_oxi_state_decorated_structure(self, structure: Structure):
"""
Get an oxidation state decorated structure. This currently works only
"""Get an oxidation state decorated structure. This currently works only
for ordered structures only.
Args:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ def __init__(self, multiple_environments_choice=None):
self.setup_parameters(multiple_environments_choice=multiple_environments_choice)

def get_structure_connectivity(self, light_structure_environments):
"""
Get the structure connectivity from the coordination environments provided
"""Get the structure connectivity from the coordination environments provided
as an input.
Args:
Expand Down
Loading

0 comments on commit 9964c4a

Please sign in to comment.