Skip to content

Commit

Permalink
format doc strings
Browse files Browse the repository at this point in the history
  • Loading branch information
janosh committed May 1, 2024
1 parent 28bd5df commit 9a3f714
Show file tree
Hide file tree
Showing 16 changed files with 54 additions and 84 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2205,11 +2205,7 @@ def add_coord_geom(
}

def __str__(self):
"""Get a string representation of the ChemicalEnvironments object.
Returns:
String representation of the ChemicalEnvironments object.
"""
"""Get a string representation of the ChemicalEnvironments."""
out = "Chemical environments object :\n"
if len(self.coord_geoms) == 0:
out += " => No coordination in it <=\n"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -699,11 +699,7 @@ def init_3points(self, non_zeros, zeros):
self.p3[zeros[1]] = 1.0

def __str__(self):
"""String representation of the Plane object
Returns:
String representation of the Plane object.
"""
"""String representation of the Plane."""
return (
f"Plane object\n => Normal vector : {self.normal_vector}\n => Equation of the plane"
f" ax + by + cz + d = 0\n with a = {self._coefficients[0]}\n "
Expand Down
22 changes: 12 additions & 10 deletions pymatgen/analysis/cost.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import itertools
import os
from collections import defaultdict
from typing import TYPE_CHECKING

import scipy.constants as const
from monty.design_patterns import singleton
Expand All @@ -21,6 +22,9 @@
from pymatgen.core import Composition, Element
from pymatgen.util.provenance import is_valid_bibtex

if TYPE_CHECKING:
from pymatgen.util.typing import CompositionLike

__author__ = "Anubhav Jain"
__copyright__ = "Copyright 2013, The Materials Project"
__version__ = "0.1"
Expand Down Expand Up @@ -145,7 +149,7 @@ def get_lowest_decomposition(self, composition):
elements = [e.symbol for e in composition.elements]
for idx in range(len(elements)):
for combi in itertools.combinations(elements, idx + 1):
chemsys = [Element(e) for e in combi]
chemsys = [Element(el) for el in combi]
x = self.costdb.get_entries(chemsys)
entries_list.extend(x)
try:
Expand All @@ -154,29 +158,27 @@ def get_lowest_decomposition(self, composition):
except IndexError:
raise ValueError("Error during PD building; most likely, cost data does not exist!")

def get_cost_per_mol(self, comp):
def get_cost_per_mol(self, comp: CompositionLike) -> float:
"""Get best estimate of minimum cost/mol based on known data.
Args:
comp:
Composition as a pymatgen.core.structure.Composition
comp (CompositionLike): chemical formula
Returns:
float of cost/mol
float: energy cost/mol
"""
comp = comp if isinstance(comp, Composition) else Composition(comp)
comp = Composition(comp)
decomp = self.get_lowest_decomposition(comp)
return sum(k.energy_per_atom * v * comp.num_atoms for k, v in decomp.items())
return sum(elem.energy_per_atom * val * comp.num_atoms for elem, val in decomp.items())

def get_cost_per_kg(self, comp):
"""Get best estimate of minimum cost/kg based on known data.
Args:
comp:
Composition as a pymatgen.core.structure.Composition
comp (CompositionLike): chemical formula
Returns:
float of cost/kg
float: energy cost/kg
"""
comp = comp if isinstance(comp, Composition) else Composition(comp)
return self.get_cost_per_mol(comp) / (comp.weight.to("kg") * const.N_A)
10 changes: 4 additions & 6 deletions pymatgen/command_line/gulp_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ def structure_lines(
written.
Returns:
string containing structure for GULP input
str: containing structure for GULP input
"""
gin = ""
if cell_flg:
Expand Down Expand Up @@ -313,8 +313,7 @@ def structure_lines(

@staticmethod
def specie_potential_lines(structure, potential, **kwargs):
"""Generate GULP input specie and potential string for pymatgen
structure.
"""Generate GULP input species and potential string for pymatgen structure.
Args:
structure: pymatgen Structure object
Expand All @@ -331,10 +330,9 @@ def specie_potential_lines(structure, potential, **kwargs):
cation_shell_chrg=float
Returns:
string containing specie and potential specification for gulp
input.
str: containing species and potential for GULP input
"""
raise NotImplementedError("gulp_specie_potential not yet implemented.\nUse library_line instead")
raise NotImplementedError("gulp_specie_potential not yet implemented. Use library_line instead")

@staticmethod
def library_line(file_name):
Expand Down
3 changes: 1 addition & 2 deletions pymatgen/core/bonds.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,7 @@ def get_bond_order(self, tol: float = 0.2, default_bl: float | None = None) -> f
(bond order = 1). If None, a ValueError will be thrown.
Returns:
Float value of bond order. For example, for C-C bond in
benzene, return 1.7.
float: value of bond order. E.g. 1.7 for C-C bond in benzene.
"""
sp1 = next(iter(self.site1.species))
sp2 = next(iter(self.site2.species))
Expand Down
12 changes: 6 additions & 6 deletions pymatgen/electronic_structure/cohp.py
Original file line number Diff line number Diff line change
Expand Up @@ -985,7 +985,7 @@ def icohpvalue(self, spin=Spin.up):

return self._icohp[spin]

def icohpvalue_orbital(self, orbitals, spin=Spin.up):
def icohpvalue_orbital(self, orbitals, spin=Spin.up) -> float:
"""
Args:
orbitals: List of Orbitals or "str(Orbital1)-str(Orbital2)"
Expand Down Expand Up @@ -1107,7 +1107,7 @@ def __str__(self) -> str:
joinstr.append(str(value))
return "\n".join(joinstr)

def get_icohp_by_label(self, label, summed_spin_channels=True, spin=Spin.up, orbitals=None):
def get_icohp_by_label(self, label, summed_spin_channels=True, spin=Spin.up, orbitals=None) -> float:
"""Get an icohp value for a certain bond as indicated by the label (bond labels starting by "1" as in
ICOHPLIST/ICOOPLIST).
Expand All @@ -1118,9 +1118,9 @@ def get_icohp_by_label(self, label, summed_spin_channels=True, spin=Spin.up, orb
orbitals: List of Orbital or "str(Orbital1)-str(Orbital2)"
Returns:
float describing ICOHP/ICOOP value
float: ICOHP/ICOOP value
"""
icohp_here = self._icohplist[label]
icohp_here: IcohpValue = self._icohplist[label]
if orbitals is None:
if summed_spin_channels:
return icohp_here.summed_icohp
Expand All @@ -1133,7 +1133,7 @@ def get_icohp_by_label(self, label, summed_spin_channels=True, spin=Spin.up, orb

return icohp_here.icohpvalue_orbital(spin=spin, orbitals=orbitals)

def get_summed_icohp_by_label_list(self, label_list, divisor=1.0, summed_spin_channels=True, spin=Spin.up):
def get_summed_icohp_by_label_list(self, label_list, divisor=1.0, summed_spin_channels=True, spin=Spin.up) -> float:
"""Get the sum of several ICOHP values that are indicated by a list of labels
(labels of the bonds are the same as in ICOHPLIST/ICOOPLIST).
Expand All @@ -1144,7 +1144,7 @@ def get_summed_icohp_by_label_list(self, label_list, divisor=1.0, summed_spin_ch
spin: if summed_spin_channels is equal to False, this spin indicates which spin channel should be returned
Returns:
float that is a sum of all ICOHPs/ICOOPs as indicated with label_list
float: sum of all ICOHPs/ICOOPs as indicated with label_list
"""
sum_icohp = 0
for label in label_list:
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/electronic_structure/dos.py
Original file line number Diff line number Diff line change
Expand Up @@ -1124,7 +1124,7 @@ def get_dos_fp(
ValueError: If type is not one of the accepted values {s/p/d/f/}summed_{pdos/tdos}.
Returns:
Fingerprint(namedtuple) : The electronic density of states fingerprint
NamedTuple: The electronic density of states fingerprint
of format (energies, densities, type, n_bins)
"""
fingerprint = namedtuple("fingerprint", "energies densities type n_bins bin_width")
Expand Down
17 changes: 6 additions & 11 deletions pymatgen/io/feff/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -584,7 +584,7 @@ def get_str(self, sort_keys: bool = False, pretty: bool = False) -> str:
pretty: Set to True for pretty aligned output. Defaults to False.
Returns:
String representation of Tags.
str: String representation of the Tags.
"""
keys = list(self)
if sort_keys:
Expand Down Expand Up @@ -744,9 +744,9 @@ def diff(self, other):
other: The other PARAMETER dictionary to compare to.
Returns:
Dict of the format {"Same" : parameters_that_are_the_same,
"Different": parameters_that_are_different} Note that the
parameters are return as full dictionaries of values.
dict[str, dict]: has format {"Same" : parameters_that_are_the_same,
"Different": parameters_that_are_different} Note that the
parameters are return as full dictionaries of values.
"""
similar_param = {}
different_param = {}
Expand Down Expand Up @@ -874,15 +874,10 @@ def pot_dict_from_str(pot_data):

def __str__(self):
"""Get a string representation of potential parameters to be used in
the feff.inp file,
determined from structure object.
The lines are arranged as follows:
the feff.inp file, determined from structure object.
The lines are arranged as follows:
ipot Z element lmax1 lmax2 stoichiometry spinph
Returns:
String representation of Atomic Coordinate Shells.
"""
central_element = Element(self.absorbing_atom)
ipotrow = [[0, central_element.Z, central_element.symbol, -1, -1, 0.0001, 0]]
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/io/gaussian.py
Original file line number Diff line number Diff line change
Expand Up @@ -1292,7 +1292,7 @@ def to_input(
are the same as GaussianInput class.
Returns:
gaunip (GaussianInput) : the gaussian input object
GaussianInput: the gaussian input object
"""
if not mol:
mol = self.final_structure
Expand Down
12 changes: 5 additions & 7 deletions pymatgen/io/icet.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,13 +203,11 @@ def get_icet_sqs_obj(self, material: Atoms | Structure, cluster_space: _ClusterS
"""Get the SQS objective function.
Args:
material (ase Atoms or pymatgen Structure) : structure to
compute SQS objective function.
Kwargs:
cluster_space (ClusterSpace) : ClusterSpace of the SQS search.
material (pymatgen.Structure | ase.Atoms): structure to compute SQS objective function for.
cluster_space (ClusterSpace): ClusterSpace of the SQS search.
Returns:
float : the SQS objective function
float: the SQS objective function
"""
if isinstance(material, Structure):
material = AseAtomsAdaptor.get_atoms(material)
Expand All @@ -228,11 +226,11 @@ def enumerate_sqs_structures(self, cluster_space: _ClusterSpace | None = None) -
Adapted from icet.tools.structure_generation.generate_sqs_by_enumeration
to accommodate multiprocessing.
Kwargs:
Args:
cluster_space (ClusterSpace) : ClusterSpace of the SQS search.
Returns:
list : a list of dicts of the form: {
list: dicts of the form: {
"structure": SQS structure,
"objective_function": SQS objective function,
}
Expand Down
15 changes: 5 additions & 10 deletions pymatgen/io/lammps/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,15 +153,11 @@ def volume(self) -> float:
return np.dot(np.cross(matrix[0], matrix[1]), matrix[2])

def get_str(self, significant_figures: int = 6) -> str:
"""Get the string representation of simulation box in LAMMPS
data file format.
"""Get the string representation of simulation box in LAMMPS data file format.
Args:
significant_figures (int): No. of significant figures to
output for box settings. Default to 6.
Returns:
String representation
"""
ph = f"{{:.{significant_figures}f}}"
lines = []
Expand Down Expand Up @@ -322,9 +318,8 @@ def structure(self) -> Structure:
)

def get_str(self, distance: int = 6, velocity: int = 8, charge: int = 4, hybrid: bool = True) -> str:
"""Get the string representation of LammpsData, essentially
the string to be written to a file. Support hybrid style
coeffs read and write.
"""Get the string representation of LammpsData, essentially the string
to be written to a file. Supports hybrid style coeffs read and write.
Args:
distance (int): No. of significant figures to output for
Expand All @@ -341,7 +336,7 @@ def get_str(self, distance: int = 6, velocity: int = 8, charge: int = 4, hybrid:
default is recommended.
Returns:
String representation
str: String representation of LammpsData.
"""
file_template = """Generated by pymatgen.io.lammps.data.LammpsData
Expand Down Expand Up @@ -1479,7 +1474,7 @@ def get_str(self, distance: int = 6, velocity: int = 8, charge: int = 4, hybrid:
default is recommended.
Returns:
String representation
str: String representation of CombinedData.
"""
lines = LammpsData.get_str(self, distance, velocity, charge, hybrid).splitlines()
info = "# " + " + ".join(
Expand Down
9 changes: 2 additions & 7 deletions pymatgen/io/lammps/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,15 +238,10 @@ def __init__(

@staticmethod
def _format_param_val(param_val) -> str:
"""
Internal method to format values in the packmol parameter dictionaries.
"""Internal method to format values in the packmol parameter dictionaries.
Args:
param_val:
Some object to turn into String
Returns:
String representation of the object
param_val (Any): Some object to turn into string
"""
if isinstance(param_val, list):
return " ".join(str(x) for x in param_val)
Expand Down
7 changes: 3 additions & 4 deletions pymatgen/io/pwmat/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,11 +288,10 @@ def get_e_tot(self) -> np.ndarray:
def get_atom_energies(self) -> np.ndarray | None:
"""Return the energies of individual atoms in material system.
Returns:
np.ndarray | None : The energies of individual atoms within the material system.
When turning on `ENERGY DEPOSITION`, PWmat will output energy per atom.
Description:
When turn on `ENERGY DEPOSITION`, PWmat will output energy per atom.
Returns:
np.ndarray | None: The energies of individual atoms within the material system.
"""
energies = []
aim_content = "Atomic-Energy, ".upper()
Expand Down
8 changes: 3 additions & 5 deletions pymatgen/io/qchem/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -551,13 +551,11 @@ def smx_template(smx: dict) -> str:

@staticmethod
def scan_template(scan: dict[str, list]) -> str:
"""
"""Get string representing Q-Chem input format for scan section.
Args:
scan (dict): Dictionary with scan section information.
Ex: {"stre": ["3 6 1.5 1.9 0.1"], "tors": ["1 2 3 4 -180 180 15"]}.
Returns:
String representing Q-Chem input format for scan section
"""
scan_list = []
scan_list.append("$scan")
Expand Down Expand Up @@ -586,7 +584,7 @@ def van_der_waals_template(radii: dict[str, float], mode: str = "atomic") -> str
**NOTE: keys must be given as strings even though they are numbers!**.
Returns:
String representing Q-Chem input format for van_der_waals section
str: representing Q-Chem input format for van_der_waals section
"""
vdw_list = []
vdw_list.append("$van_der_waals")
Expand Down
5 changes: 2 additions & 3 deletions pymatgen/io/vasp/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -532,8 +532,7 @@ def get_str(
vasp4_compatible: bool = False,
significant_figures: int = 16,
) -> str:
"""
Return a string to be written as a POSCAR file. By default, site
"""Return a string to be written as a POSCAR file. By default, site
symbols are written, which is compatible for vasp >= 5.
Args:
Expand All @@ -548,7 +547,7 @@ def get_str(
scientific format.
Returns:
String representation of POSCAR.
str: representation of POSCAR.
"""
# This corrects for VASP really annoying bug of crashing on lattices
# which have triple product < 0. We will just invert the lattice
Expand Down
Loading

0 comments on commit 9a3f714

Please sign in to comment.