Skip to content

Commit

Permalink
refactor data file paths
Browse files Browse the repository at this point in the history
  • Loading branch information
janosh committed Nov 15, 2023
1 parent 637ada0 commit 3ebcbad
Show file tree
Hide file tree
Showing 7 changed files with 99 additions and 100 deletions.
3 changes: 2 additions & 1 deletion pymatgen/analysis/hhi.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
__date__ = "Oct 27, 2014"


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


@singleton
Expand Down
12 changes: 6 additions & 6 deletions pymatgen/analysis/local_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,16 +46,16 @@
__status__ = "Production"
__date__ = "August 17, 2017"

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

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

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

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


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

# Load elemental radii table
bonds_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "bonds_jmol_ob.yaml")
bonds_file = f"{module_dir}/bonds_jmol_ob.yaml"
with open(bonds_file) as f:
yaml = YAML()
self.el_radius = yaml.load(f)
Expand Down Expand Up @@ -4210,7 +4210,7 @@ def from_preset(cls, preset) -> CutOffDictNN:
A CutOffDictNN using the preset cut-off dictionary.
"""
if preset == "vesta_2019":
cut_offs = loadfn(f"{_directory}/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
6 changes: 3 additions & 3 deletions pymatgen/analysis/prototypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from pymatgen.core import Structure

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


@due.dcite(
Expand Down Expand Up @@ -66,8 +66,8 @@ def __init__(self, initial_ltol=0.2, initial_stol=0.3, initial_angle_tol=5):
def _match_prototype(structure_matcher, structure):
tags = []
for d in AFLOW_PROTOTYPE_LIBRARY:
p = d["snl"].structure
match = structure_matcher.fit_anonymous(p, structure)
struct = d["snl"].structure
match = structure_matcher.fit_anonymous(struct, structure)
if match:
tags.append(d)
return tags
Expand Down
3 changes: 2 additions & 1 deletion pymatgen/io/lammps/generators.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
__version__ = "0.2"

logger = logging.getLogger(__name__)
template_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates")
module_dir = os.path.dirname(os.path.abspath(__file__))
template_dir = f"{module_dir}/templates"


@dataclass
Expand Down
7 changes: 4 additions & 3 deletions pymatgen/io/lammps/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@
__email__ = "[email protected], [email protected]"
__date__ = "Nov 2022"

module_dir = os.path.dirname(os.path.abspath(__file__))
template_dir = f"{module_dir}/templates"


class LammpsInputFile(InputFile):
"""
Expand Down Expand Up @@ -868,8 +871,6 @@ class LammpsRun(MSONable):
templates.
"""

template_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates")

def __init__(self, script_template: str, settings: dict, data: LammpsData | str, script_filename: str) -> None:
"""
Base constructor.
Expand Down Expand Up @@ -931,7 +932,7 @@ def md(
other_settings (dict): other settings to be filled into
placeholders.
"""
template_path = os.path.join(cls.template_dir, "md.template")
template_path = os.path.join(template_dir, "md.template")
with open(template_path) as f:
script_template = f.read()
settings = other_settings.copy() if other_settings else {}
Expand Down
3 changes: 2 additions & 1 deletion pymatgen/io/lammps/sets.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
__version__ = "0.2"

logger = logging.getLogger(__name__)
template_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates")
module_dir = os.path.dirname(os.path.abspath(__file__))
template_dir = f"{module_dir}/templates"


class LammpsInputSet(InputSet):
Expand Down
165 changes: 80 additions & 85 deletions tests/io/vasp/test_outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -1466,49 +1466,49 @@ def test_interpolation(self):
class TestProcar(PymatgenTest):
def test_init(self):
filepath = f"{TEST_FILES_DIR}/PROCAR.simple"
p = Procar(filepath)
assert p.get_occupation(0, "d")[Spin.up] == approx(0)
assert p.get_occupation(0, "s")[Spin.up] == approx(0.35381249999999997)
assert p.get_occupation(0, "p")[Spin.up] == approx(1.19540625)
procar = Procar(filepath)
assert procar.get_occupation(0, "d")[Spin.up] == approx(0)
assert procar.get_occupation(0, "s")[Spin.up] == approx(0.35381249999999997)
assert procar.get_occupation(0, "p")[Spin.up] == approx(1.19540625)
with pytest.raises(ValueError, match="'m' is not in list"):
p.get_occupation(1, "m")
assert p.nbands == 10
assert p.nkpoints == 10
assert p.nions == 3
procar.get_occupation(1, "m")
assert procar.nbands == 10
assert procar.nkpoints == 10
assert procar.nions == 3
filepath = f"{TEST_FILES_DIR}/PROCAR"
p = Procar(filepath)
assert p.get_occupation(0, "dxy")[Spin.up] == approx(0.96214813853000025)
assert p.get_occupation(0, "dxy")[Spin.down] == approx(0.85796295426000124)
procar = Procar(filepath)
assert procar.get_occupation(0, "dxy")[Spin.up] == approx(0.96214813853000025)
assert procar.get_occupation(0, "dxy")[Spin.down] == approx(0.85796295426000124)

def test_phase_factors(self):
filepath = f"{TEST_FILES_DIR}/PROCAR.phase"
p = Procar(filepath)
assert p.phase_factors[Spin.up][0, 0, 0, 0] == approx(-0.746 + 0.099j)
assert p.phase_factors[Spin.down][0, 0, 0, 0] == approx(0.372 - 0.654j)
procar = Procar(filepath)
assert procar.phase_factors[Spin.up][0, 0, 0, 0] == approx(-0.746 + 0.099j)
assert procar.phase_factors[Spin.down][0, 0, 0, 0] == approx(0.372 - 0.654j)

# Two Li should have same phase factor.
assert p.phase_factors[Spin.up][0, 0, 0, 0] == approx(p.phase_factors[Spin.up][0, 0, 1, 0])
assert p.phase_factors[Spin.up][0, 0, 2, 0] == approx(-0.053 + 0.007j)
assert p.phase_factors[Spin.down][0, 0, 2, 0] == approx(0.027 - 0.047j)
assert procar.phase_factors[Spin.up][0, 0, 0, 0] == approx(procar.phase_factors[Spin.up][0, 0, 1, 0])
assert procar.phase_factors[Spin.up][0, 0, 2, 0] == approx(-0.053 + 0.007j)
assert procar.phase_factors[Spin.down][0, 0, 2, 0] == approx(0.027 - 0.047j)

# new style phase factors (VASP 5.4.4+)
filepath = f"{TEST_FILES_DIR}/PROCAR.new_format_5.4.4"
p = Procar(filepath)
assert p.phase_factors[Spin.up][0, 0, 0, 0] == approx(-0.13 + 0.199j)
procar = Procar(filepath)
assert procar.phase_factors[Spin.up][0, 0, 0, 0] == approx(-0.13 + 0.199j)

def test_get_projection_on_elements(self):
filepath = f"{TEST_FILES_DIR}/PROCAR.simple"
p = Procar(filepath)
procar = Procar(filepath)
struct = Structure(
Lattice.cubic(3.0),
["Li", "Na", "K"],
[[0.0, 0.0, 0.0], [0.25, 0.25, 0.25], [0.75, 0.75, 0.75]],
)
d = p.get_projection_on_elements(struct)
assert d[Spin.up][2][2] == approx({"Na": 0.042, "K": 0.646, "Li": 0.042})
dct = procar.get_projection_on_elements(struct)
assert dct[Spin.up][2][2] == approx({"Na": 0.042, "K": 0.646, "Li": 0.042})
# https://github.com/materialsproject/pymatgen/pull/3261
struct.replace_species({"K": "Na"})
d2 = p.get_projection_on_elements(struct)
d2 = procar.get_projection_on_elements(struct)
assert d2[Spin.up][2][2] == approx({"Na": 0.688, "Li": 0.042})


Expand Down Expand Up @@ -1556,47 +1556,42 @@ def test_init(self):

class TestWavecar(PymatgenTest):
def setUp(self):
a = np.array([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]])
self.vol = np.dot(a[0, :], np.cross(a[1, :], a[2, :]))
b = np.array(
[
np.cross(a[1, :], a[2, :]),
np.cross(a[2, :], a[0, :]),
np.cross(a[0, :], a[1, :]),
]
)
a = np.array([[10, 0, 0], [0, 10, 0], [0, 0, 10]], dtype=float) # lattice vectors
self.vol = np.dot(a[0, :], np.cross(a[1, :], a[2, :])) # unit cell volume
# reciprocal lattice vectors
b = np.array([np.cross(a[1, :], a[2, :]), np.cross(a[2, :], a[0, :]), np.cross(a[0, :], a[1, :])])
self.b = 2 * np.pi * b / self.vol
self.a = a
self.w = Wavecar(f"{TEST_FILES_DIR}/WAVECAR.N2")
self.wavecar = Wavecar(f"{TEST_FILES_DIR}/WAVECAR.N2")
self.wH2 = Wavecar(f"{TEST_FILES_DIR}/WAVECAR.H2_low_symm")
self.wH2_gamma = Wavecar(f"{TEST_FILES_DIR}/WAVECAR.H2_low_symm.gamma")
self.w_ncl = Wavecar(f"{TEST_FILES_DIR}/WAVECAR.H2.ncl")
self.w_frac_encut = Wavecar(f"{TEST_FILES_DIR}/WAVECAR.frac_encut")

def test_standard(self):
w = self.w
wavecar = self.wavecar
a = np.array([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]])
vol = np.dot(a[0, :], np.cross(a[1, :], a[2, :]))
b = np.array([np.cross(a[1, :], a[2, :]), np.cross(a[2, :], a[0, :]), np.cross(a[0, :], a[1, :])])
b = 2 * np.pi * b / vol

assert w.filename == f"{TEST_FILES_DIR}/WAVECAR.N2"
assert w.efermi == approx(-5.7232, abs=1e-4)
assert w.encut == 25.0
assert w.nb == 9
assert w.nk == 1
assert_allclose(w.a, a)
assert_allclose(w.b, b)
assert w.vol == approx(vol)
assert len(w.kpoints) == w.nk
assert len(w.coeffs) == w.nk
assert len(w.coeffs[0]) == w.nb
assert len(w.band_energy) == w.nk
assert w.band_energy[0].shape == (w.nb, 3)
assert len(w.Gpoints[0]) <= 257
for k in range(w.nk):
for b in range(w.nb):
assert len(w.coeffs[k][b]) == len(w.Gpoints[k])
assert wavecar.filename == f"{TEST_FILES_DIR}/WAVECAR.N2"
assert wavecar.efermi == approx(-5.7232, abs=1e-4)
assert wavecar.encut == 25.0
assert wavecar.nb == 9
assert wavecar.nk == 1
assert_allclose(wavecar.a, a)
assert_allclose(wavecar.b, b)
assert wavecar.vol == approx(vol)
assert len(wavecar.kpoints) == wavecar.nk
assert len(wavecar.coeffs) == wavecar.nk
assert len(wavecar.coeffs[0]) == wavecar.nb
assert len(wavecar.band_energy) == wavecar.nk
assert wavecar.band_energy[0].shape == (wavecar.nb, 3)
assert len(wavecar.Gpoints[0]) <= 257
for k in range(wavecar.nk):
for b in range(wavecar.nb):
assert len(wavecar.coeffs[k][b]) == len(wavecar.Gpoints[k])

# Test WAVECAR with fractional encut
assert self.w_frac_encut.encut == 100.5
Expand Down Expand Up @@ -1624,21 +1619,21 @@ def test_standard(self):
sys.stdout = saved_stdout

def test_n2_45210(self):
w = Wavecar(f"{TEST_FILES_DIR}/WAVECAR.N2.45210")
assert w.filename == f"{TEST_FILES_DIR}/WAVECAR.N2.45210"
assert w.efermi == approx(-5.7232, abs=1e-4)
assert w.encut == 25.0
assert w.nb == 9
assert w.nk == 1
assert_allclose(w.a, self.a)
assert_allclose(w.b, self.b)
assert w.vol == approx(self.vol)
assert len(w.kpoints) == w.nk
assert len(w.coeffs) == w.nk
assert len(w.coeffs[0]) == w.nb
assert len(w.band_energy) == w.nk
assert w.band_energy[0].shape == (w.nb, 3)
assert len(w.Gpoints[0]) <= 257
wavecar = Wavecar(f"{TEST_FILES_DIR}/WAVECAR.N2.45210")
assert wavecar.filename == f"{TEST_FILES_DIR}/WAVECAR.N2.45210"
assert wavecar.efermi == approx(-5.7232, abs=1e-4)
assert wavecar.encut == 25.0
assert wavecar.nb == 9
assert wavecar.nk == 1
assert_allclose(wavecar.a, self.a)
assert_allclose(wavecar.b, self.b)
assert wavecar.vol == approx(self.vol)
assert len(wavecar.kpoints) == wavecar.nk
assert len(wavecar.coeffs) == wavecar.nk
assert len(wavecar.coeffs[0]) == wavecar.nb
assert len(wavecar.band_energy) == wavecar.nk
assert wavecar.band_energy[0].shape == (wavecar.nb, 3)
assert len(wavecar.Gpoints[0]) <= 257

def test_n2_spin(self):
w = Wavecar(f"{TEST_FILES_DIR}/WAVECAR.N2.spin")
Expand All @@ -1658,21 +1653,21 @@ def test_n2_spin(self):
Wavecar._generate_G_points = temp_ggp

def test_generate_nbmax(self):
self.w._generate_nbmax()
assert self.w._nbmax.tolist() == [5, 5, 5]
self.wavecar._generate_nbmax()
assert self.wavecar._nbmax.tolist() == [5, 5, 5]

def test_generate_g_points(self):
for k in range(self.w.nk):
kp = self.w.kpoints[k]
assert len(self.w._generate_G_points(kp)) <= 257
for k in range(self.wavecar.nk):
kp = self.wavecar.kpoints[k]
assert len(self.wavecar._generate_G_points(kp)) <= 257

def test_evaluate_wavefunc(self):
self.w.Gpoints.append(np.array([0, 0, 0]))
self.w.kpoints.append(np.array([0, 0, 0]))
self.w.coeffs.append([[1 + 1j]])
assert self.w.evaluate_wavefunc(-1, -1, [0, 0, 0]) == approx((1 + 1j) / np.sqrt(self.vol), abs=1e-4)
assert self.w.evaluate_wavefunc(0, 0, [0, 0, 0]) == approx(
np.sum(self.w.coeffs[0][0]) / np.sqrt(self.vol), abs=1e-4
self.wavecar.Gpoints.append(np.array([0, 0, 0]))
self.wavecar.kpoints.append(np.array([0, 0, 0]))
self.wavecar.coeffs.append([[1 + 1j]])
assert self.wavecar.evaluate_wavefunc(-1, -1, [0, 0, 0]) == approx((1 + 1j) / np.sqrt(self.vol), abs=1e-4)
assert self.wavecar.evaluate_wavefunc(0, 0, [0, 0, 0]) == approx(
np.sum(self.wavecar.coeffs[0][0]) / np.sqrt(self.vol), abs=1e-4
)
w = Wavecar(f"{TEST_FILES_DIR}/WAVECAR.N2.spin")
w.Gpoints.append(np.array([0, 0, 0]))
Expand All @@ -1681,11 +1676,11 @@ def test_evaluate_wavefunc(self):
assert w.evaluate_wavefunc(-1, -1, [0, 0, 0]) == approx((1 + 1j) / np.sqrt(self.vol), abs=1e-4)

def test_fft_mesh_basic(self):
mesh = self.w.fft_mesh(0, 5)
mesh = self.wavecar.fft_mesh(0, 5)
ind = np.argmax(np.abs(mesh))
assert np.unravel_index(ind, mesh.shape) == (14, 1, 1)
assert mesh[tuple((self.w.ng / 2).astype(int))] == 0j
mesh = self.w.fft_mesh(0, 5, shift=False)
assert mesh[tuple((self.wavecar.ng / 2).astype(int))] == 0j
mesh = self.wavecar.fft_mesh(0, 5, shift=False)
ind = np.argmax(np.abs(mesh))
assert np.unravel_index(ind, mesh.shape) == (6, 8, 8)
assert mesh[0, 0, 0] == 0j
Expand Down Expand Up @@ -1744,7 +1739,7 @@ def test_fft_mesh_advanced(self):
def test_get_parchg(self):
poscar = Poscar.from_file(f"{TEST_FILES_DIR}/POSCAR")

w = self.w
w = self.wavecar
c = w.get_parchg(poscar, 0, 0, spin=0, phase=False)
assert "total" in c.data
assert "diff" not in c.data
Expand Down Expand Up @@ -1803,17 +1798,17 @@ def test_write_unks(self):
unk_ncl = Unk.from_file(f"{TEST_FILES_DIR}/UNK.H2.ncl")

with pytest.raises(ValueError, match="invalid directory"):
self.w.write_unks(f"{TEST_FILES_DIR}/UNK.N2.std")
self.wavecar.write_unks(f"{TEST_FILES_DIR}/UNK.N2.std")

# different grids
self.w.write_unks("./unk_dir")
self.wavecar.write_unks("./unk_dir")
assert len(list(Path("./unk_dir").glob("UNK*"))) == 1
unk = Unk.from_file("./unk_dir/UNK00001.1")
assert unk != unk_std

# correct grid
self.w.ng = np.array([12, 12, 12])
self.w.write_unks(".")
self.wavecar.ng = np.array([12, 12, 12])
self.wavecar.write_unks(".")
unk = Unk.from_file("UNK00001.1")
assert unk == unk_std

Expand Down

0 comments on commit 3ebcbad

Please sign in to comment.