Skip to content

Commit

Permalink
Docstring tweaks for io.vasp.inputs and format tweaks for some othe…
Browse files Browse the repository at this point in the history
…r parts (#3996)

* docstring tweaks

* fix typo

* reduce indentation level

* fix vasp case to VASP

* use walrus operator

* revert overlapping functional changes from #3994

* my bad, I get confused hopping between two PRs

* remove debug code from vasp.help

* fix `use-named-expression` with sourcery

* clean up Vasprun.as_dict

* simplify dict generation

* re-raise and update -> |=

* simplify logic conditions

* remove unused logger

* remove a lot of unused logger, wondering if they exist for a reason?

* remove some unused module_dir, they must have gone stranded

* CAPS LOCK ENGAGED: Go up! module level variables!
  • Loading branch information
DanielYang59 authored Aug 14, 2024
1 parent b28c937 commit cadcae4
Show file tree
Hide file tree
Showing 60 changed files with 280 additions and 398 deletions.
3 changes: 1 addition & 2 deletions src/pymatgen/alchemy/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,7 @@ def test(self, structure: Structure):
all_species = set(self.specie_and_min_dist)
for site in structure:
species = set(site.species)
sp_to_test = species.intersection(all_species)
if sp_to_test:
if sp_to_test := species.intersection(all_species):
max_r = max(self.specie_and_min_dist[sp] for sp in sp_to_test)
neighbors = structure.get_neighbors(site, max_r)
for sp in sp_to_test:
Expand Down
3 changes: 0 additions & 3 deletions src/pymatgen/analysis/bond_dissociation.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from __future__ import annotations

import logging
import warnings
from typing import cast

Expand All @@ -23,8 +22,6 @@
__status__ = "Alpha"
__date__ = "7/26/18"

logger = logging.getLogger(__name__)


class BondDissociationEnergies(MSONable):
"""
Expand Down
6 changes: 3 additions & 3 deletions src/pymatgen/analysis/bond_valence.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,15 @@
# JACS, 1991, 113(9), 3226-3229. doi:10.1021/ja00009a002.
ELECTRONEG = [Element(sym) for sym in "H B C Si N P As Sb O S Se Te F Cl Br I".split()]

module_dir = os.path.dirname(os.path.abspath(__file__))
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))

# Read in BV parameters.
BV_PARAMS = {}
for key, val in loadfn(f"{module_dir}/bvparam_1991.yaml").items():
for key, val in loadfn(f"{MODULE_DIR}/bvparam_1991.yaml").items():
BV_PARAMS[Element(key)] = val

# Read in YAML containing data-mined ICSD BV data.
all_data = loadfn(f"{module_dir}/icsd_bv.yaml")
all_data = loadfn(f"{MODULE_DIR}/icsd_bv.yaml")
ICSD_BV_DATA = {Species.from_str(sp): data for sp, data in all_data["bvsum"].items()}
PRIOR_PROB = {Species.from_str(sp): data for sp, data in all_data["occurrence"].items()}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from __future__ import annotations

import abc
import os
from typing import TYPE_CHECKING

import numpy as np
Expand Down Expand Up @@ -43,8 +42,6 @@
__email__ = "david.waroquiers@gmail.com"
__date__ = "Feb 20, 2016"

module_dir = os.path.dirname(os.path.abspath(__file__))

MPSYMBOL_TO_CN = AllCoordinationGeometries().get_symbol_cn_mapping()
ALLCG = AllCoordinationGeometries()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
__email__ = "david.waroquiers@gmail.com"
__date__ = "Feb 20, 2016"

module_dir = os.path.dirname(os.path.abspath(__file__))
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))

UNKNOWN_ENVIRONMENT_SYMBOL = "UNKNOWN"
UNCLEAR_ENVIRONMENT_SYMBOL = "UNCLEAR"
Expand Down Expand Up @@ -850,17 +850,17 @@ def __init__(self, permutations_safe_override=False, only_symbols=None):
dict.__init__(self)
self.cg_list: list[CoordinationGeometry] = []
if only_symbols is None:
with open(f"{module_dir}/coordination_geometries_files/allcg.txt") as file:
with open(f"{MODULE_DIR}/coordination_geometries_files/allcg.txt") as file:
data = file.readlines()
for line in data:
cg_file = f"{module_dir}/{line.strip()}"
cg_file = f"{MODULE_DIR}/{line.strip()}"
with open(cg_file) as file:
dd = json.load(file)
self.cg_list.append(CoordinationGeometry.from_dict(dd))
else:
for symbol in only_symbols:
fsymbol = symbol.replace(":", "#")
cg_file = f"{module_dir}/coordination_geometries_files/{fsymbol}.json"
cg_file = f"{MODULE_DIR}/coordination_geometries_files/{fsymbol}.json"
with open(cg_file) as file:
dd = json.load(file)
self.cg_list.append(CoordinationGeometry.from_dict(dd))
Expand Down
4 changes: 2 additions & 2 deletions src/pymatgen/analysis/cost.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
__email__ = "ajain@lbl.gov"
__date__ = "Aug 27, 2013"

module_dir = os.path.dirname(os.path.abspath(__file__))
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))


class CostEntry(PDEntry):
Expand Down Expand Up @@ -112,7 +112,7 @@ class CostDBElements(CostDBCSV):
"""Singleton that provides the cost data for elements."""

def __init__(self):
CostDBCSV.__init__(self, f"{module_dir}/costdb_elements.csv")
CostDBCSV.__init__(self, f"{MODULE_DIR}/costdb_elements.csv")


class CostAnalyzer:
Expand Down
4 changes: 2 additions & 2 deletions src/pymatgen/analysis/diffraction/tem.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@
__date__ = "03/31/2020"


module_dir = os.path.dirname(__file__)
with open(f"{module_dir}/atomic_scattering_params.json", encoding="utf-8") as file:
MODULE_DIR = os.path.dirname(__file__)
with open(f"{MODULE_DIR}/atomic_scattering_params.json", encoding="utf-8") as file:
ATOMIC_SCATTERING_PARAMS = json.load(file)


Expand Down
3 changes: 0 additions & 3 deletions src/pymatgen/analysis/fragmenter.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from __future__ import annotations

import copy
import logging
from typing import TYPE_CHECKING

from monty.json import MSONable
Expand All @@ -23,8 +22,6 @@
__status__ = "Beta"
__date__ = "8/21/19"

logger = logging.getLogger(__name__)


class Fragmenter(MSONable):
"""Molecule fragmenter class."""
Expand Down
15 changes: 5 additions & 10 deletions src/pymatgen/analysis/graphs.py
Original file line number Diff line number Diff line change
Expand Up @@ -429,8 +429,7 @@ def add_edge(
# there should only ever be at most one edge
# between a given (site, jimage) pair and another
# (site, jimage) pair
existing_edge_data = self.graph.get_edge_data(from_index, to_index)
if existing_edge_data:
if existing_edge_data := self.graph.get_edge_data(from_index, to_index):
for d in existing_edge_data.values():
if d["to_jimage"] == to_jimage:
if warn_duplicates:
Expand Down Expand Up @@ -1287,12 +1286,10 @@ def __rmul__(self, other):
def _edges_to_str(cls, g) -> str:
header = "from to to_image "
header_line = "---- ---- ------------"
edge_weight_name = g.graph["edge_weight_name"]
if edge_weight_name:
if g.graph["edge_weight_name"]:
print_weights = True
edge_label = g.graph["edge_weight_name"]
edge_weight_units = g.graph["edge_weight_units"]
if edge_weight_units:
if edge_weight_units := g.graph["edge_weight_units"]:
edge_label += f" ({edge_weight_units})"
header += f" {edge_label}"
header_line += f" {'-' * max([18, len(edge_label)])}"
Expand Down Expand Up @@ -2673,12 +2670,10 @@ def from_dict(cls, dct: dict) -> Self:
def _edges_to_str(cls, g):
header = "from to to_image "
header_line = "---- ---- ------------"
edge_weight_name = g.graph["edge_weight_name"]
if edge_weight_name:
if g.graph["edge_weight_name"]:
print_weights = ["weight"]
edge_label = g.graph["edge_weight_name"]
edge_weight_units = g.graph["edge_weight_units"]
if edge_weight_units:
if edge_weight_units := g.graph["edge_weight_units"]:
edge_label += f" ({edge_weight_units})"
header += f" {edge_label}"
header_line += f" {'-' * max([18, len(edge_label)])}"
Expand Down
6 changes: 3 additions & 3 deletions src/pymatgen/analysis/hhi.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@
__date__ = "Oct 27, 2014"


module_dir = os.path.dirname(os.path.abspath(__file__))
csv_path = f"{module_dir}/hhi_data.csv"
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
HHI_CSV_PATH = f"{MODULE_DIR}/hhi_data.csv"


@singleton
Expand All @@ -37,7 +37,7 @@ def __init__(self):
"""Init for HHIModel."""
self.symbol_hhip_hhir = {} # symbol->(HHI_production, HHI reserve)

with open(csv_path) as file:
with open(HHI_CSV_PATH) as file:
for line in file:
if line[0] != "#":
symbol, hhi_production, hhi_reserve = line.split(",")
Expand Down
12 changes: 6 additions & 6 deletions src/pymatgen/analysis/local_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,16 +50,16 @@
__status__ = "Production"
__date__ = "August 17, 2017"

module_dir = os.path.dirname(os.path.abspath(__file__))
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
yaml = YAML()

with open(f"{module_dir}/op_params.yaml") as file:
with open(f"{MODULE_DIR}/op_params.yaml") as file:
default_op_params = yaml.load(file)

with open(f"{module_dir}/cn_opt_params.yaml") as file:
with open(f"{MODULE_DIR}/cn_opt_params.yaml") as file:
cn_opt_params = yaml.load(file)

with open(f"{module_dir}/ionic_radii.json") as file:
with open(f"{MODULE_DIR}/ionic_radii.json") as file:
_ion_radii = json.load(file)


Expand Down Expand Up @@ -1211,7 +1211,7 @@ def __init__(
self.min_bond_distance = min_bond_distance

# Load elemental radii table
bonds_file = f"{module_dir}/bonds_jmol_ob.yaml"
bonds_file = f"{MODULE_DIR}/bonds_jmol_ob.yaml"
with open(bonds_file) as file:
yaml = YAML()
self.el_radius = yaml.load(file)
Expand Down Expand Up @@ -4226,7 +4226,7 @@ def from_preset(cls, preset) -> Self:
A CutOffDictNN using the preset cut-off dictionary.
"""
if preset == "vesta_2019":
cut_offs = loadfn(f"{module_dir}/vesta_cutoffs.yaml")
cut_offs = loadfn(f"{MODULE_DIR}/vesta_cutoffs.yaml")
return cls(cut_off_dict=cut_offs)

raise ValueError(f"Unknown {preset=}")
Expand Down
3 changes: 1 addition & 2 deletions src/pymatgen/analysis/pourbaix_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -604,8 +604,7 @@ def _preprocess_pourbaix_entries(self, entries, nproc=None):
else:
# Serial processing of multi-entry generation
for combo in all_combos:
multi_entry = self.process_multientry(combo, prod_comp=tot_comp)
if multi_entry:
if multi_entry := self.process_multientry(combo, prod_comp=tot_comp):
multi_entries.append(multi_entry)

return multi_entries
Expand Down
4 changes: 2 additions & 2 deletions src/pymatgen/analysis/prototypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@
if TYPE_CHECKING:
from pymatgen.core import Structure

module_dir = os.path.dirname(os.path.abspath(__file__))
AFLOW_PROTOTYPE_LIBRARY = loadfn(f"{module_dir}/aflow_prototypes.json")
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
AFLOW_PROTOTYPE_LIBRARY = loadfn(f"{MODULE_DIR}/aflow_prototypes.json")


@due.dcite(
Expand Down
4 changes: 0 additions & 4 deletions src/pymatgen/analysis/reaction_calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from __future__ import annotations

import logging
import re
from itertools import chain, combinations
from typing import TYPE_CHECKING, no_type_check, overload
Expand Down Expand Up @@ -32,9 +31,6 @@
__date__ = "Jul 11 2012"


logger = logging.getLogger(__name__)


class BalancedReaction(MSONable):
"""Represent a complete chemical reaction."""

Expand Down
10 changes: 3 additions & 7 deletions src/pymatgen/analysis/structure_matcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -968,8 +968,7 @@ def get_rms_anonymous(self, struct1, struct2):
struct1, struct2 = self._process_species([struct1, struct2])
struct1, struct2, fu, s1_supercell = self._preprocess(struct1, struct2)

matches = self._anonymous_match(struct1, struct2, fu, s1_supercell, use_rms=True, break_on_match=False)
if matches:
if matches := self._anonymous_match(struct1, struct2, fu, s1_supercell, use_rms=True, break_on_match=False):
best = min(matches, key=lambda x: x[1][0])
return best[1][0], best[0]

Expand All @@ -993,9 +992,7 @@ def get_best_electronegativity_anonymous_mapping(self, struct1: Structure, struc
struct1, struct2 = self._process_species([struct1, struct2])
struct1, struct2, fu, s1_supercell = self._preprocess(struct1, struct2)

matches = self._anonymous_match(struct1, struct2, fu, s1_supercell, use_rms=True, break_on_match=True)

if matches:
if matches := self._anonymous_match(struct1, struct2, fu, s1_supercell, use_rms=True, break_on_match=True):
min_X_diff = np.inf
best = None
for match in matches:
Expand Down Expand Up @@ -1027,8 +1024,7 @@ def get_all_anonymous_mappings(self, struct1, struct2, niggli=True, include_dist
struct1, struct2 = self._process_species([struct1, struct2])
struct1, struct2, fu, s1_supercell = self._preprocess(struct1, struct2, niggli)

matches = self._anonymous_match(struct1, struct2, fu, s1_supercell, break_on_match=not include_dist)
if matches:
if matches := self._anonymous_match(struct1, struct2, fu, s1_supercell, break_on_match=not include_dist):
if include_dist:
return [(m[0], m[1][0]) for m in matches]

Expand Down
3 changes: 1 addition & 2 deletions src/pymatgen/analysis/transition_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,8 +248,7 @@ def from_dir(cls, root_dir, relaxation_dirs=None, **kwargs) -> Self:
if terminal:
for ds in terminal_dirs:
od = ds[0] if idx == 0 else ds[1]
outcar = glob(f"{od}/OUTCAR*")
if outcar:
if outcar := glob(f"{od}/OUTCAR*"):
outcar = sorted(outcar)
outcars.append(Outcar(outcar[-1]))
break
Expand Down
3 changes: 1 addition & 2 deletions src/pymatgen/apps/borg/hive.py
Original file line number Diff line number Diff line change
Expand Up @@ -418,8 +418,7 @@ def from_dict(cls, dct: dict) -> Self:

def _get_transformation_history(path):
"""Check for a transformations.json* file and returns the history."""
trans_json = glob(f"{path}/transformations.json*")
if trans_json:
if trans_json := glob(f"{path}/transformations.json*"):
try:
with zopen(trans_json[0]) as file:
return json.load(file)["history"]
Expand Down
3 changes: 1 addition & 2 deletions src/pymatgen/apps/borg/queen.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,7 @@ def load_data(self, filename):
def order_assimilation(args):
"""Internal helper method for BorgQueen to process assimilation."""
path, drone, data, status = args
new_data = drone.assimilate(path)
if new_data:
if new_data := drone.assimilate(path):
data.append(json.dumps(new_data, cls=MontyEncoder))
status["count"] += 1
count = status["count"]
Expand Down
11 changes: 5 additions & 6 deletions src/pymatgen/command_line/critic2_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,17 +277,16 @@ def from_path(cls, path, suffix="", zpsp=None) -> Self:
chgcar = Chgcar.from_file(chgcar_path)
chgcar_ref = None

if not zpsp:
potcar_path = get_filepath(
if not zpsp and (
potcar_path := get_filepath(
"POTCAR",
"Could not find POTCAR, will not be able to calculate charge transfer.",
path,
suffix,
)

if potcar_path:
potcar = Potcar.from_file(potcar_path)
zpsp = {p.element: p.zval for p in potcar}
):
potcar = Potcar.from_file(potcar_path)
zpsp = {p.element: p.zval for p in potcar}

if not zpsp:
# try and get reference "all-electron-like" charge density if zpsp not present
Expand Down
4 changes: 2 additions & 2 deletions src/pymatgen/command_line/gulp_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
__status__ = "Production"
__date__ = "Jun 22, 2013M"

module_dir = os.path.dirname(os.path.abspath(__file__))
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))

_anions = set(map(Element, ["O", "S", "F", "Cl", "Br", "N", "P"]))
_cations = set(
Expand Down Expand Up @@ -868,7 +868,7 @@ class TersoffPotential:

def __init__(self):
"""Init TersoffPotential."""
with open(f"{module_dir}/OxideTersoffPotentials") as file:
with open(f"{MODULE_DIR}/OxideTersoffPotentials") as file:
data = {}
for row in file:
metaloxi = row.split()[0]
Expand Down
4 changes: 2 additions & 2 deletions src/pymatgen/core/composition.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@

from pymatgen.util.typing import SpeciesLike

module_dir = os.path.dirname(os.path.abspath(__file__))
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))


@total_ordering
Expand Down Expand Up @@ -959,7 +959,7 @@ def _get_oxi_state_guesses(

# Load prior probabilities of oxidation states, used to rank solutions
if not type(self).oxi_prob:
all_data = loadfn(f"{module_dir}/../analysis/icsd_bv.yaml")
all_data = loadfn(f"{MODULE_DIR}/../analysis/icsd_bv.yaml")
type(self).oxi_prob = {Species.from_str(sp): data for sp, data in all_data["occurrence"].items()}
oxi_states_override = oxi_states_override or {}
# Assert Composition only has integer amounts
Expand Down
Loading

0 comments on commit cadcae4

Please sign in to comment.