Skip to content

Commit

Permalink
let env vars override .pmgrc.yaml in _load_pmg_settings()
Browse files Browse the repository at this point in the history
  • Loading branch information
janosh committed Oct 21, 2022
1 parent 2b58ba0 commit b53d22e
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 22 deletions.
26 changes: 14 additions & 12 deletions pymatgen/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
operations on them.
"""

from __future__ import annotations

import os
import warnings

Expand All @@ -29,28 +31,28 @@
SETTINGS_FILE = os.path.join(os.path.expanduser("~"), ".pmgrc.yaml")


def _load_pmg_settings():
# Load environment variables by default as backup
d = {}
for k, v in os.environ.items():
if k.startswith("PMG_"):
d[k] = v
elif k in ["VASP_PSP_DIR", "MAPI_KEY", "DEFAULT_FUNCTIONAL"]:
d["PMG_" + k] = v

# Override anything in env vars with that in yml file
def _load_pmg_settings() -> dict[str, str]:
settings = {}
# Load .pmgrc.yaml file
if os.path.exists(SETTINGS_FILE):
try:
yaml = YAML()
with open(SETTINGS_FILE) as f:
d_yml = yaml.load(f)
d.update(d_yml)
settings.update(d_yml)
except Exception as ex:
# If there are any errors, default to using environment variables
# if present.
warnings.warn(f"Error loading .pmgrc.yaml: {ex}. You may need to reconfigure your yaml file.")

return d
# Override .pmgrc.yaml with env vars if present
for k, v in os.environ.items():
if k.startswith("PMG_"):
settings[k] = v
elif k in ["VASP_PSP_DIR", "MAPI_KEY", "DEFAULT_FUNCTIONAL"]:
settings["PMG_" + k] = v

return settings


SETTINGS = _load_pmg_settings()
Expand Down
17 changes: 7 additions & 10 deletions pymatgen/io/vasp/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -470,7 +470,6 @@ def get_string(self, direct: bool = True, vasp4_compatible: bool = False, signif
Returns:
String 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
# vectors.
Expand Down Expand Up @@ -1244,12 +1243,9 @@ def automatic_gamma_density(structure: Structure, kppa: float):
reciprocal lattice vector proportional to its length.
Args:
structure:
Input structure
kppa:
Grid density
structure: Input structure
kppa: Grid density
"""

latt = structure.lattice
lengths = latt.abc
ngrid = kppa / structure.num_sites
Expand Down Expand Up @@ -1889,8 +1885,8 @@ def from_symbol_and_functional(symbol: str, functional: str = None):
:param functional: E.g., PBE
:return: PotcarSingle
"""
if functional is None:
functional = SETTINGS.get("PMG_DEFAULT_FUNCTIONAL", "PBE")
functional = functional or SETTINGS.get("PMG_DEFAULT_FUNCTIONAL", "PBE")
assert isinstance(functional, str) # type narrowing
funcdir = PotcarSingle.functional_dir[functional]
d = SETTINGS.get("PMG_VASP_PSP_DIR")
if d is None:
Expand Down Expand Up @@ -2158,7 +2154,6 @@ def __getattr__(self, a):
For float type properties, they are converted to the correct float. By
default, all energies in eV and all length scales are in Angstroms.
"""

try:
return self.keywords[a.upper()]
except Exception:
Expand Down Expand Up @@ -2420,7 +2415,9 @@ def run_vasp(
:param err_file: File to write err.
"""
self.write_input(output_dir=run_dir)
vasp_cmd = vasp_cmd or SETTINGS.get("PMG_VASP_EXE")
vasp_cmd = vasp_cmd or SETTINGS.get("PMG_VASP_EXE") # type: ignore[assignment]
if not vasp_cmd:
raise ValueError("No VASP executable specified!")
vasp_cmd = [os.path.expanduser(os.path.expandvars(t)) for t in vasp_cmd]
if not vasp_cmd:
raise RuntimeError("You need to supply vasp_cmd or set the PMG_VASP_EXE in .pmgrc.yaml to run VASP.")
Expand Down

0 comments on commit b53d22e

Please sign in to comment.