Skip to content

Commit

Permalink
f-string path construction everywhere, no need for os.path.join(...) (
Browse files Browse the repository at this point in the history
#3229)

* simplify: f-string path construction everywhere, no need for os.path.join(...)

* fix _get_oxid_state_guesses doc str

* rename to _get_oxi_state_guesses
  • Loading branch information
janosh authored Aug 7, 2023
1 parent 1fa96f8 commit 23e0613
Show file tree
Hide file tree
Showing 84 changed files with 558 additions and 600 deletions.
4 changes: 2 additions & 2 deletions dev_scripts/regen_libxcfunc.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def main():

# Generate new json file in pycore
pmg_core = os.path.abspath("../pymatgen/core/")
json_path = os.path.join(pmg_core, "libxc_docs.json")
json_path = f"{pmg_core}/libxc_docs.json"
write_libxc_docs_json(xc_funcs, json_path)

# Build new enum list.
Expand All @@ -101,7 +101,7 @@ def main():

# Re-generate enumerations.
# [0] read py module.
xc_funcpy_path = os.path.join(pmg_core, "libxcfunc.py")
xc_funcpy_path = f"{pmg_core}/libxcfunc.py"
with open(xc_funcpy_path) as fh:
lines = fh.readlines()

Expand Down
3 changes: 1 addition & 2 deletions pymatgen/alchemy/materials.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@

import datetime
import json
import os
import re
from typing import TYPE_CHECKING, Any
from warnings import warn
Expand Down Expand Up @@ -217,7 +216,7 @@ def write_vasp_input(
**kwargs: All keyword args supported by the VASP input set.
"""
vasp_input_set(self.final_structure, **kwargs).write_input(output_dir, make_dir_if_not_present=create_directory)
with open(os.path.join(output_dir, "transformations.json"), "w") as fp:
with open(f"{output_dir}/transformations.json", "w") as fp:
json.dump(self.as_dict(), fp)

def __str__(self) -> str:
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/analysis/bond_valence.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@

# Read in BV parameters.
BV_PARAMS = {}
for key, val in loadfn(os.path.join(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(os.path.join(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
2 changes: 1 addition & 1 deletion pymatgen/analysis/cost.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ class CostDBElements(CostDBCSV):

def __init__(self):
"""Init."""
CostDBCSV.__init__(self, os.path.join(module_dir, "costdb_elements.csv"))
CostDBCSV.__init__(self, f"{module_dir}/costdb_elements.csv")


class CostAnalyzer:
Expand Down
8 changes: 4 additions & 4 deletions pymatgen/analysis/local_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,13 @@
_directory = os.path.join(os.path.dirname(__file__))
yaml = YAML()

with open(os.path.join(_directory, "op_params.yaml")) as f:
with open(f"{_directory}/op_params.yaml") as f:
default_op_params = yaml.load(f)

with open(os.path.join(_directory, "cn_opt_params.yaml")) as f:
with open(f"{_directory}/cn_opt_params.yaml") as f:
cn_opt_params = yaml.load(f)

with open(os.path.join(_directory, "ionic_radii.json")) as fp:
with open(f"{_directory}/ionic_radii.json") as fp:
_ion_radii = json.load(fp)


Expand Down Expand Up @@ -4218,7 +4218,7 @@ def from_preset(preset):
A CutOffDictNN using the preset cut-off dictionary.
"""
if preset == "vesta_2019":
cut_offs = loadfn(os.path.join(_directory, "vesta_cutoffs.yaml"))
cut_offs = loadfn(f"{_directory}/vesta_cutoffs.yaml")
return CutOffDictNN(cut_off_dict=cut_offs)

raise ValueError(f"Unknown {preset=}")
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/analysis/magnetism/analyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,10 @@
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))

try:
DEFAULT_MAGMOMS = loadfn(os.path.join(MODULE_DIR, "default_magmoms.yaml"))
DEFAULT_MAGMOMS = loadfn(f"{MODULE_DIR}/default_magmoms.yaml")
except Exception:
warnings.warn("Could not load default_magmoms.yaml, falling back to VASPIncarBase.yaml")
DEFAULT_MAGMOMS = loadfn(os.path.join(MODULE_DIR, "../../io/vasp/VASPIncarBase.yaml"))
DEFAULT_MAGMOMS = loadfn(f"{MODULE_DIR}/../../io/vasp/VASPIncarBase.yaml")
DEFAULT_MAGMOMS = DEFAULT_MAGMOMS["MAGMOM"]


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def __init__(self, lambda_table=None, alpha=-5):
self._lambda_table = lambda_table
else:
module_dir = os.path.dirname(__file__)
json_file = os.path.join(module_dir, "data", "lambda.json")
json_file = f"{module_dir}/data/lambda.json"
with open(json_file) as f:
self._lambda_table = json.load(f)

Expand Down
2 changes: 1 addition & 1 deletion pymatgen/analysis/structure_prediction/volume_predictor.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from pymatgen.core import Structure

MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
bond_params = loadfn(os.path.join(MODULE_DIR, "DLS_bond_params.yaml"))
bond_params = loadfn(f"{MODULE_DIR}/DLS_bond_params.yaml")


def _is_ox(structure):
Expand Down
8 changes: 4 additions & 4 deletions pymatgen/analysis/transition_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,14 +252,14 @@ def from_dir(cls, root_dir, relaxation_dirs=None, **kwargs):
terminal_dirs.append([os.path.join(root_dir, d) for d in ["initial", "final"]])

for i, d in neb_dirs:
outcar = glob(os.path.join(d, "OUTCAR*"))
contcar = glob(os.path.join(d, "CONTCAR*"))
poscar = glob(os.path.join(d, "POSCAR*"))
outcar = glob(f"{d}/OUTCAR*")
contcar = glob(f"{d}/CONTCAR*")
poscar = glob(f"{d}/POSCAR*")
terminal = i in [0, neb_dirs[-1][0]]
if terminal:
for ds in terminal_dirs:
od = ds[0] if i == 0 else ds[1]
outcar = glob(os.path.join(od, "OUTCAR*"))
outcar = glob(f"{od}/OUTCAR*")
if outcar:
outcar = sorted(outcar)
outcars.append(Outcar(outcar[-1]))
Expand Down
14 changes: 7 additions & 7 deletions pymatgen/apps/borg/hive.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,9 @@ def assimilate(self, path):
"""
files = os.listdir(path)
if "relax1" in files and "relax2" in files:
filepath = glob(os.path.join(path, "relax2", "vasprun.xml*"))[0]
filepath = glob(f"{path}/relax2/vasprun.xml*")[0]
else:
vasprun_files = glob(os.path.join(path, "vasprun.xml*"))
vasprun_files = glob(f"{path}/vasprun.xml*")
filepath = None
if len(vasprun_files) == 1:
filepath = vasprun_files[0]
Expand Down Expand Up @@ -157,8 +157,8 @@ def get_valid_paths(self, path):
(not parent.endswith("/relax1"))
and (not parent.endswith("/relax2"))
and (
len(glob(os.path.join(parent, "vasprun.xml*"))) > 0
or (len(glob(os.path.join(parent, "POSCAR*"))) > 0 and len(glob(os.path.join(parent, "OSZICAR*"))) > 0)
len(glob(f"{parent}/vasprun.xml*")) > 0
or (len(glob(f"{parent}/POSCAR*")) > 0 and len(glob(f"{parent}/OSZICAR*")) > 0)
)
):
return [parent]
Expand Down Expand Up @@ -225,10 +225,10 @@ def assimilate(self, path):
filenames = {"INCAR", "POTCAR", "CONTCAR", "OSZICAR", "POSCAR", "DYNMAT"}
if "relax1" in files and "relax2" in files:
for filename in ("INCAR", "POTCAR", "POSCAR"):
search_str = os.path.join(path, "relax1", filename + "*")
search_str = f"{path}/relax1", filename + "*"
files_to_parse[filename] = glob(search_str)[0]
for filename in ("CONTCAR", "OSZICAR"):
search_str = os.path.join(path, "relax2", filename + "*")
search_str = f"{path}/relax2", filename + "*"
files_to_parse[filename] = glob(search_str)[-1]
else:
for filename in filenames:
Expand Down Expand Up @@ -427,7 +427,7 @@ def from_dict(cls, dct):

def _get_transformation_history(path):
"""Checks for a transformations.json* file and returns the history."""
trans_json = glob(os.path.join(path, "transformations.json*"))
trans_json = glob(f"{path}/transformations.json*")
if trans_json:
try:
with zopen(trans_json[0]) as f:
Expand Down
10 changes: 5 additions & 5 deletions pymatgen/cli/pmg_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ def setup_cp2k_data(cp2k_data_dirs: list[str]) -> None:
from pymatgen.io.cp2k.inputs import GaussianTypeOrbitalBasisSet, GthPotential
from pymatgen.io.cp2k.utils import chunk

basis_files = glob(os.path.join(data_dir, "*BASIS*"))
potential_files = glob(os.path.join(data_dir, "*POTENTIAL*"))
basis_files = glob(f"{data_dir}/*BASIS*")
potential_files = glob(f"{data_dir}/*POTENTIAL*")

settings: dict[str, dict] = {str(el): {"potentials": {}, "basis_sets": {}} for el in Element}

Expand Down Expand Up @@ -158,7 +158,7 @@ def setup_potcars(potcar_dirs: list[str]):
if subdir == "Osmium":
subdir = "Os"
dest = os.path.join(base_dir, f"POTCAR.{subdir}")
shutil.move(os.path.join(base_dir, "POTCAR"), dest)
shutil.move(f"{base_dir}/POTCAR", dest)
with subprocess.Popen(["gzip", "-f", dest]) as p:
p.communicate()
except Exception as exc:
Expand All @@ -181,10 +181,10 @@ def build_enum(fortran_command: str = "gfortran") -> bool:
state = True
try:
subprocess.call(["git", "clone", "--recursive", "https://github.com/msg-byu/enumlib.git"])
os.chdir(os.path.join(cwd, "enumlib", "symlib", "src"))
os.chdir(f"{cwd}/enumlib/symlib/src")
os.environ["F90"] = fortran_command
subprocess.call(["make"])
enumpath = os.path.join(cwd, "enumlib", "src")
enumpath = f"{cwd}/enumlib/src"
os.chdir(enumpath)
subprocess.call(["make"])
subprocess.call(["make", "enum.x"])
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/cli/pmg_potcar.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def gen_potcar(dirname, filename):
elements = f.readlines()
symbols = [el.strip() for el in elements if el.strip() != ""]
potcar = Potcar(symbols)
potcar.write_file(os.path.join(dirname, "POTCAR"))
potcar.write_file(f"{dirname}/POTCAR")


def generate_potcar(args):
Expand Down
8 changes: 4 additions & 4 deletions pymatgen/command_line/bader_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -490,17 +490,17 @@ def bader_analysis_from_objects(chgcar, potcar=None, aeccar0=None, aeccar2=None)
if aeccar0 and aeccar2:
# construct reference file
chgref = aeccar0.linear_add(aeccar2)
chgref_path = os.path.join(tmp_dir, "CHGCAR_ref")
chgref_path = f"{tmp_dir}/CHGCAR_ref"
chgref.write_file(chgref_path)
else:
chgref_path = None

chgcar.write_file("CHGCAR")
chgcar_path = os.path.join(tmp_dir, "CHGCAR")
chgcar_path = f"{tmp_dir}/CHGCAR"

if potcar:
potcar.write_file("POTCAR")
potcar_path = os.path.join(tmp_dir, "POTCAR")
potcar_path = f"{tmp_dir}/POTCAR"
else:
potcar_path = None

Expand Down Expand Up @@ -530,7 +530,7 @@ def bader_analysis_from_objects(chgcar, potcar=None, aeccar0=None, aeccar2=None)
chgcar.is_spin_polarized = False
chgcar.write_file("CHGCAR_mag")

chgcar_mag_path = os.path.join(tmp_dir, "CHGCAR_mag")
chgcar_mag_path = f"{tmp_dir}/CHGCAR_mag"
ba = BaderAnalysis(
chgcar_filename=chgcar_mag_path,
potcar_filename=potcar_path,
Expand Down
14 changes: 7 additions & 7 deletions pymatgen/command_line/chargemol_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,42 +219,42 @@ def _from_data_dir(self, chargemol_output_path=None):
if chargemol_output_path is None:
chargemol_output_path = ""

charge_path = os.path.join(chargemol_output_path, "DDEC6_even_tempered_net_atomic_charges.xyz")
charge_path = f"{chargemol_output_path}/DDEC6_even_tempered_net_atomic_charges.xyz"
self.ddec_charges = self._get_data_from_xyz(charge_path)
self.dipoles = self._get_dipole_info(charge_path)

bond_order_path = os.path.join(chargemol_output_path, "DDEC6_even_tempered_bond_orders.xyz")
bond_order_path = f"{chargemol_output_path}/DDEC6_even_tempered_bond_orders.xyz"
if os.path.exists(bond_order_path):
self.bond_order_sums = self._get_data_from_xyz(bond_order_path)
self.bond_order_dict = self._get_bond_order_info(bond_order_path)
else:
self.bond_order_sums = self.bond_order_dict = None

spin_moment_path = os.path.join(chargemol_output_path, "DDEC6_even_tempered_atomic_spin_moments.xyz")
spin_moment_path = f"{chargemol_output_path}/DDEC6_even_tempered_atomic_spin_moments.xyz"
if os.path.exists(spin_moment_path):
self.ddec_spin_moments = self._get_data_from_xyz(spin_moment_path)
else:
self.ddec_spin_moments = None

rsquared_path = os.path.join(chargemol_output_path, "DDEC_atomic_Rsquared_moments.xyz")
rsquared_path = f"{chargemol_output_path}/DDEC_atomic_Rsquared_moments.xyz"
if os.path.exists(rsquared_path):
self.ddec_rsquared_moments = self._get_data_from_xyz(rsquared_path)
else:
self.ddec_rsquared_moments = None

rcubed_path = os.path.join(chargemol_output_path, "DDEC_atomic_Rcubed_moments.xyz")
rcubed_path = f"{chargemol_output_path}/DDEC_atomic_Rcubed_moments.xyz"
if os.path.exists(rcubed_path):
self.ddec_rcubed_moments = self._get_data_from_xyz(rcubed_path)
else:
self.ddec_rcubed_moments = None

rfourth_path = os.path.join(chargemol_output_path, "DDEC_atomic_Rfourth_moments.xyz")
rfourth_path = f"{chargemol_output_path}/DDEC_atomic_Rfourth_moments.xyz"
if os.path.exists(rfourth_path):
self.ddec_rfourth_moments = self._get_data_from_xyz(rfourth_path)
else:
self.ddec_rfourth_moments = None

ddec_analysis_path = os.path.join(chargemol_output_path, "VASP_DDEC_analysis.output")
ddec_analysis_path = f"{chargemol_output_path}/VASP_DDEC_analysis.output"
if os.path.exists(ddec_analysis_path):
self.cm5_charges = self._get_cm5_data_from_output(ddec_analysis_path)
else:
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/command_line/gulp_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -881,7 +881,7 @@ class TersoffPotential:
def __init__(self):
"""Init TersoffPotential."""
module_dir = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(module_dir, "OxideTersoffPotentials")) as f:
with open(f"{module_dir}/OxideTersoffPotentials") as f:
data = {}
for row in f:
metaloxi = row.split()[0]
Expand Down
19 changes: 7 additions & 12 deletions pymatgen/core/composition.py
Original file line number Diff line number Diff line change
Expand Up @@ -751,7 +751,7 @@ def oxi_state_guesses(
oxidation state across all sites in that composition. If the
composition is not charge balanced, an empty list is returned.
"""
return self._get_oxid_state_guesses(all_oxi_states, max_sites, oxi_states_override, target_charge)[0]
return self._get_oxi_state_guesses(all_oxi_states, max_sites, oxi_states_override, target_charge)[0]

def replace(self, elem_map: dict[str, str | dict[str, int | float]]) -> Composition:
"""
Expand Down Expand Up @@ -843,9 +843,7 @@ def add_charges_from_oxi_state_guesses(
on the results form guessing oxidation states. If no oxidation state
is possible, returns a Composition where all oxidation states are 0.
"""
_, oxidation_states = self._get_oxid_state_guesses(
all_oxi_states, max_sites, oxi_states_override, target_charge
)
_, oxidation_states = self._get_oxi_state_guesses(all_oxi_states, max_sites, oxi_states_override, target_charge)

# Special case: No charged compound is possible
if not oxidation_states:
Expand All @@ -872,7 +870,7 @@ def remove_charges(self) -> Composition:
dct[Element(specie.symbol)] += amt
return Composition(dct)

def _get_oxid_state_guesses(self, all_oxi_states, max_sites, oxi_states_override, target_charge):
def _get_oxi_state_guesses(self, all_oxi_states, max_sites, oxi_states_override, target_charge):
"""
Utility operation for guessing oxidation states.
Expand All @@ -898,13 +896,10 @@ def _get_oxid_state_guesses(self, all_oxi_states, max_sites, oxi_states_override
formula is greater than abs(max_sites).
Returns:
A list of dicts - each dict reports an element symbol and average
oxidation state across all sites in that composition. If the
composition is not charge balanced, an empty list is returned.
A list of dicts - each dict maps the element symbol to a list of
list[dict]: Each dict maps the element symbol to a list of
oxidation states for each site of that element. For example, Fe3O4 could
return a list of [2,2,2,3,3,3] for the oxidation states of If the composition
is
return a list of [2,2,2,3,3,3] for the oxidation states of the 6 Fe sites.
If the composition is not charge balanced, an empty list is returned.
"""
comp = self.copy()
# reduce Composition if necessary
Expand All @@ -925,7 +920,7 @@ def _get_oxid_state_guesses(self, all_oxi_states, max_sites, oxi_states_override
# Load prior probabilities of oxidation states, used to rank solutions
if not Composition.oxi_prob:
module_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)))
all_data = loadfn(os.path.join(module_dir, "..", "analysis", "icsd_bv.yaml"))
all_data = loadfn(f"{module_dir}/../analysis/icsd_bv.yaml")
Composition.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
2 changes: 1 addition & 1 deletion pymatgen/core/ion.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ def oxi_state_guesses( # type: ignore
oxidation state across all sites in that composition. If the
composition is not charge balanced, an empty list is returned.
"""
return self._get_oxid_state_guesses(all_oxi_states, max_sites, oxi_states_override, self.charge)[0]
return self._get_oxi_state_guesses(all_oxi_states, max_sites, oxi_states_override, self.charge)[0]

def __eq__(self, other: object) -> bool:
if not isinstance(other, Ion):
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/core/surface.py
Original file line number Diff line number Diff line change
Expand Up @@ -1327,7 +1327,7 @@ def nonstoichiometric_symmetrized_slab(self, init_slab):


module_dir = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(module_dir, "reconstructions_archive.json")) as data_file:
with open(f"{module_dir}/reconstructions_archive.json") as data_file:
reconstructions_archive = json.load(data_file)


Expand Down
Loading

0 comments on commit 23e0613

Please sign in to comment.