Skip to content

Commit

Permalink
staticmethod to classmethod where applicable
Browse files Browse the repository at this point in the history
  • Loading branch information
janosh committed Sep 13, 2023
1 parent 46d4aba commit a6c0569
Show file tree
Hide file tree
Showing 11 changed files with 63 additions and 104 deletions.
28 changes: 14 additions & 14 deletions pymatgen/alchemy/transmuters.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,8 +204,8 @@ def append_transformed_structures(self, trafo_structs_or_transmuter):
assert isinstance(ts, TransformedStructure)
self.transformed_structures.extend(trafo_structs_or_transmuter)

@staticmethod
def from_structures(structures, transformations=None, extend_collection=0):
@classmethod
def from_structures(cls, structures, transformations=None, extend_collection=0):
"""Alternative constructor from structures rather than
TransformedStructures.
Expand All @@ -222,7 +222,7 @@ def from_structures(structures, transformations=None, extend_collection=0):
StandardTransmuter
"""
trafo_struct = [TransformedStructure(s, []) for s in structures]
return StandardTransmuter(trafo_struct, transformations, extend_collection)
return cls(trafo_struct, transformations, extend_collection)


class CifTransmuter(StandardTransmuter):
Expand All @@ -235,7 +235,7 @@ def __init__(self, cif_string, transformations=None, primitive=True, extend_coll
containing multiple structures.
Args:
cif_string: A string containing a cif or a series of cifs
cif_string: A string containing a cif or a series of CIFs
transformations: New transformations to be applied to all
structures
primitive: Whether to generate the primitive cell from the cif.
Expand All @@ -259,8 +259,8 @@ def __init__(self, cif_string, transformations=None, primitive=True, extend_coll
transformed_structures.append(trafo_struct)
super().__init__(transformed_structures, transformations, extend_collection)

@staticmethod
def from_filenames(filenames, transformations=None, primitive=True, extend_collection=False):
@classmethod
def from_filenames(cls, filenames, transformations=None, primitive=True, extend_collection=False):
"""Generates a TransformedStructureCollection from a cif, possibly
containing multiple structures.
Expand All @@ -271,12 +271,12 @@ def from_filenames(filenames, transformations=None, primitive=True, extend_colle
primitive: Same meaning as in __init__.
extend_collection: Same meaning as in __init__.
"""
allcifs = []
cif_files = []
for fname in filenames:
with open(fname) as f:
allcifs.append(f.read())
return CifTransmuter(
"\n".join(allcifs),
with open(fname) as file:
cif_files.append(file.read())
return cls(
"\n".join(cif_files),
transformations,
primitive=primitive,
extend_collection=extend_collection,
Expand All @@ -298,8 +298,8 @@ def __init__(self, poscar_string, transformations=None, extend_collection=False)
trafo_struct = TransformedStructure.from_poscar_string(poscar_string, [])
super().__init__([trafo_struct], transformations, extend_collection=extend_collection)

@staticmethod
def from_filenames(poscar_filenames, transformations=None, extend_collection=False):
@classmethod
def from_filenames(cls, poscar_filenames, transformations=None, extend_collection=False):
"""Convenient constructor to generates a POSCAR transmuter from a list of
POSCAR filenames.
Expand All @@ -314,7 +314,7 @@ def from_filenames(poscar_filenames, transformations=None, extend_collection=Fal
for filename in poscar_filenames:
with open(filename) as f:
trafo_structs.append(TransformedStructure.from_poscar_string(f.read(), []))
return StandardTransmuter(trafo_structs, transformations, extend_collection=extend_collection)
return cls(trafo_structs, transformations, extend_collection=extend_collection)


def batch_write_vasp_input(
Expand Down
6 changes: 3 additions & 3 deletions pymatgen/analysis/local_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -4195,8 +4195,8 @@ def extend_structure_molecules(self):
"""
return True

@staticmethod
def from_preset(preset):
@classmethod
def from_preset(cls, preset):
"""
Initialize a CutOffDictNN according to a preset set of cut-offs.
Expand All @@ -4211,7 +4211,7 @@ def from_preset(preset):
"""
if preset == "vesta_2019":
cut_offs = loadfn(f"{_directory}/vesta_cutoffs.yaml")
return CutOffDictNN(cut_off_dict=cut_offs)
return cls(cut_off_dict=cut_offs)

raise ValueError(f"Unknown {preset=}")

Expand Down
11 changes: 5 additions & 6 deletions pymatgen/analysis/reaction_calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,28 +249,27 @@ def from_dict(cls, d):
def from_string(cls, *args, **kwargs):
return cls.from_str(*args, **kwargs)

@staticmethod
def from_str(rxn_string):
@classmethod
def from_str(cls, rxn_str):
"""
Generates a balanced reaction from a string. The reaction must
already be balanced.
Args:
rxn_string:
The reaction string. For example, "4 Li + O2-> 2Li2O"
rxn_string (str): The reaction string. For example, "4 Li + O2 -> 2Li2O"
Returns:
BalancedReaction
"""
rct_str, prod_str = rxn_string.split("->")
rct_str, prod_str = rxn_str.split("->")

def get_comp_amt(comp_str):
return {
Composition(m.group(2)): float(m.group(1) or 1)
for m in re.finditer(r"([\d\.]*(?:[eE]-?[\d\.]+)?)\s*([A-Z][\w\.\(\)]*)", comp_str)
}

return BalancedReaction(get_comp_amt(rct_str), get_comp_amt(prod_str))
return cls(get_comp_amt(rct_str), get_comp_amt(prod_str))


class Reaction(BalancedReaction):
Expand Down
31 changes: 18 additions & 13 deletions pymatgen/analysis/surface_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,10 +325,12 @@ def create_slab_label(self):
label += f", {self.get_monolayer:.3f} ML"
return label

@staticmethod
def from_computed_structure_entry(entry, miller_index, label=None, adsorbates=None, clean_entry=None, **kwargs):
@classmethod
def from_computed_structure_entry(
cls, entry, miller_index, label=None, adsorbates=None, clean_entry=None, **kwargs
):
"""Returns SlabEntry from a ComputedStructureEntry."""
return SlabEntry(
return cls(
entry.structure,
entry.energy,
miller_index,
Expand Down Expand Up @@ -1560,23 +1562,26 @@ def is_converged(self, min_points_frac=0.015, tol: float = 0.0025):
all_flat.append(True)
return all(all_flat)

@staticmethod
def from_files(poscar_filename, locpot_filename, outcar_filename, shift=0, blength=3.5):
@classmethod
def from_files(cls, poscar_filename, locpot_filename, outcar_filename, shift=0, blength=3.5):
"""
:param poscar_filename: POSCAR file
:param locpot_filename: LOCPOT file
:param outcar_filename: OUTCAR file
:param shift: shift
:param blength: The longest bond length in the material.
Used to handle pbc for noncontiguous slab layers
Initializes a WorkFunctionAnalyzer from POSCAR, LOCPOT, and OUTCAR files.
Args:
poscar_filename (str): The path to the POSCAR file.
locpot_filename (str): The path to the LOCPOT file.
outcar_filename (str): The path to the OUTCAR file.
shift (float): The shift value. Defaults to 0.
blength (float): The longest bond length in the material.
Used to handle pbc for noncontiguous slab layers. Defaults to 3.5.
Returns:
WorkFunctionAnalyzer
WorkFunctionAnalyzer: A WorkFunctionAnalyzer instance.
"""
poscar = Poscar.from_file(poscar_filename)
locpot = Locpot.from_file(locpot_filename)
outcar = Outcar(outcar_filename)
return WorkFunctionAnalyzer(
return cls(
poscar.structure,
locpot.get_average_along_axis(2),
outcar.efermi,
Expand Down
12 changes: 4 additions & 8 deletions pymatgen/core/libxcfunc.py
Original file line number Diff line number Diff line change
Expand Up @@ -485,18 +485,14 @@ def as_dict(self):
"""Makes LibxcFunc obey the general json interface used in pymatgen for
easier serialization.
"""
return {
"name": self.name,
"@module": type(self).__module__,
"@class": type(self).__name__,
}
return {"name": self.name, "@module": type(self).__module__, "@class": type(self).__name__}

@staticmethod
def from_dict(d):
@classmethod
def from_dict(cls, dct):
"""Makes LibxcFunc obey the general json interface used in pymatgen for
easier serialization.
"""
return LibxcFunc[d["name"]]
return cls[dct["name"]]

def to_json(self):
"""Returns a json string representation of the MSONable object."""
Expand Down
3 changes: 1 addition & 2 deletions pymatgen/core/periodic_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -493,8 +493,7 @@ def from_name(name: str) -> Element:
"""Get an element from its long name.
Args:
name: Long name of the element, e.g. 'Hydrogen' or
'Iron'. Not case-sensitive.
name: Long name of the element, e.g. 'Hydrogen' or 'Iron'. Not case-sensitive.
Returns:
Element with the name 'name'
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/core/structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -2611,7 +2611,7 @@ def to(self, filename: str = "", fmt: str = "", **kwargs) -> str:
Non-case sensitive.
**kwargs: Kwargs passthru to relevant methods. E.g., This allows
the passing of parameters like symprec to the
CifWriter.__init__ method for generation of symmetric cifs.
CifWriter.__init__ method for generation of symmetric CIFs.
Returns:
str: String representation of molecule in given format. If a filename
Expand Down Expand Up @@ -2786,7 +2786,7 @@ def from_file(cls, filename, primitive=False, sort=False, merge_tol=0.0, **kwarg
Args:
filename (str): The filename to read from.
primitive (bool): Whether to convert to a primitive cell. Only available for cifs. Defaults to False.
primitive (bool): Whether to convert to a primitive cell. Only available for CIFs. Defaults to False.
sort (bool): Whether to sort sites. Default to False.
merge_tol (float): If this is some positive number, sites that are within merge_tol from each other will be
merged. Usually 0.01 should be enough to deal with common numerical issues.
Expand Down
42 changes: 4 additions & 38 deletions pymatgen/electronic_structure/boltztrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -1943,41 +1943,9 @@ def from_files(path_dir, dos_spin=1):
if run_type == "BOLTZ":
dos, pdos = BoltztrapAnalyzer.parse_transdos(path_dir, efermi, dos_spin=dos_spin, trim_dos=False)

(
mu_steps,
cond,
seebeck,
kappa,
hall,
pn_doping_levels,
mu_doping,
seebeck_doping,
cond_doping,
kappa_doping,
hall_doping,
carrier_conc,
) = BoltztrapAnalyzer.parse_cond_and_hall(path_dir, doping_levels)

return BoltztrapAnalyzer(
gap,
mu_steps,
cond,
seebeck,
kappa,
hall,
pn_doping_levels,
mu_doping,
seebeck_doping,
cond_doping,
kappa_doping,
hall_doping,
intrans,
dos,
pdos,
carrier_conc,
vol,
warning,
)
*cond_and_hall, carrier_conc = BoltztrapAnalyzer.parse_cond_and_hall(path_dir, doping_levels)

return BoltztrapAnalyzer(gap, *cond_and_hall, intrans, dos, pdos, carrier_conc, vol, warning)

if run_type == "DOS":
trim = intrans["dos_type"] == "HISTO"
Expand All @@ -1991,8 +1959,6 @@ def from_files(path_dir, dos_spin=1):
return BoltztrapAnalyzer(bz_bands=bz_bands, bz_kpoints=bz_kpoints, warning=warning, vol=vol)

if run_type == "FERMI":
""" """

if os.path.exists(f"{path_dir}/boltztrap_BZ.cube"):
fs_data = read_cube_file(f"{path_dir}/boltztrap_BZ.cube")
elif os.path.exists(f"{path_dir}/fort.30"):
Expand All @@ -2001,7 +1967,7 @@ def from_files(path_dir, dos_spin=1):
raise BoltztrapError("No data file found for fermi surface")
return BoltztrapAnalyzer(fermi_surface_data=fs_data)

raise ValueError(f"Run type: {run_type} not recognized!")
raise ValueError(f"{run_type=} not recognized!")

def as_dict(self):
"""MSONable dict."""
Expand Down
25 changes: 12 additions & 13 deletions pymatgen/electronic_structure/boltztrap2.py
Original file line number Diff line number Diff line change
Expand Up @@ -884,19 +884,18 @@ def save(self, fname="bztTranspProps.json.gz"):
]

if self.contain_props_doping:
lst_props.extend(
[
self.Conductivity_doping,
self.Seebeck_doping,
self.Kappa_doping,
self.Power_Factor_doping,
self.Effective_mass_doping,
self.Carriers_conc_doping,
self.doping,
self.mu_doping,
self.mu_doping_eV,
]
)
props = [
self.Conductivity_doping,
self.Seebeck_doping,
self.Kappa_doping,
self.Power_Factor_doping,
self.Effective_mass_doping,
self.Carriers_conc_doping,
self.doping,
self.mu_doping,
self.mu_doping_eV,
]
lst_props.extend(props)
dumpfn(lst_props, fname)

def load(self, fname="bztTranspProps.json.gz"):
Expand Down
3 changes: 0 additions & 3 deletions pymatgen/electronic_structure/plotter.py
Original file line number Diff line number Diff line change
Expand Up @@ -2926,7 +2926,6 @@ def plot_seebeck_mu(self, temp: float = 600, output: str = "eig", xlim: Sequence
output (str): "eig" or "average"
xlim (tuple[float, float]): a 2-tuple of min and max fermi energy. Defaults to (0, band gap)
Returns:
a matplotlib object
"""
Expand Down Expand Up @@ -2965,7 +2964,6 @@ def plot_conductivity_mu(
units of relaxation time
xlim (tuple[float, float]): a 2-tuple of min and max fermi energy. Defaults to (0, band gap)
Returns:
a matplotlib object
"""
Expand Down Expand Up @@ -3004,7 +3002,6 @@ def plot_power_factor_mu(
units of relaxation time
xlim (tuple[float, float]): a 2-tuple of min and max fermi energy. Defaults to (0, band gap)
Returns:
a matplotlib object
"""
Expand Down
2 changes: 0 additions & 2 deletions pymatgen/transformations/advanced_transformations.py
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,6 @@ 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:
Depending on returned_ranked list, either a transformed structure
or a list of dictionaries, where each dictionary is of the form
Expand Down Expand Up @@ -1015,7 +1014,6 @@ 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:
[{"structure": Structure, "energy": float}]
"""
Expand Down

0 comments on commit a6c0569

Please sign in to comment.