Skip to content

Commit

Permalink
Merge pull request #20 from benrich37/cleanup
Browse files Browse the repository at this point in the history
Cleanup
  • Loading branch information
benrich37 authored Nov 11, 2024
2 parents 0dd1922 + 82fd73f commit b6d183c
Show file tree
Hide file tree
Showing 11 changed files with 178 additions and 376 deletions.
21 changes: 0 additions & 21 deletions src/pymatgen/io/jdftx/outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,9 +331,6 @@ class JDFTXOutfile:
__getattr__(name: str) -> Any
Returns the value of the property with the same name as the input string.
__dir__() -> list[str]
Returns a list of all the properties of the JDFTXOutfile object.
__str__() -> str
Returns a string representation of the JDFTXOutfile object.
"""
Expand Down Expand Up @@ -1312,24 +1309,6 @@ def __getattr__(self, name: str) -> Any:
# If the attribute is not found in either, raise an AttributeError
raise AttributeError(f"{self.__class__.__name__} not found: {name}")

def __dir__(self) -> list:
"""List attributes.
Returns a list of attributes for the object, including those from
self.slices[-1].
Returns
-------
list
A list of attribute names
"""
# Get the default attributes
default_attrs = dir(self)
# Get the attributes from self.slices[-1] if slices is not empty
slice_attrs = dir(self.slices[-1]) if self.slices else []
# Combine and return unique attributes
return list(set(default_attrs + slice_attrs))

def __str__(self) -> str:
"""Return string representation of JDFTXOutfile object.
Expand Down
80 changes: 80 additions & 0 deletions tests/io/jdftx/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,3 +291,83 @@ def jdftxoutfile_matches_known(joutfile: JDFTXOutfile, known: dict):
"e": -17.265553748795949 * Ha_to_eV,
"elec_grad_k": 2.991e-07,
}


ex_outfileslice1_fname = ex_files_dir / "ex_out_slice_latmin"
ex_outfileslice2_fname = ex_files_dir / "ex_out_slice_ionmin"
with open(ex_outfileslice1_fname) as f:
ex_outfileslice1 = list.copy(list(f))
with open(ex_outfileslice2_fname) as f:
ex_outfileslice2 = list.copy(list(f))

ex_jstruc_slice_fname1 = ex_files_dir / "ex_text_slice_forJAtoms_latmin"
ex_jstruc_slice1 = []
with open(ex_jstruc_slice_fname1) as f:
ex_jstruc_slice1 = list.copy(list(f))


ex_jstruc_slice_fname2 = ex_files_dir / "ex_text_slice_forJAtoms_latmin2"
ex_jstruc_slice2 = []
with open(ex_jstruc_slice_fname2) as f:
ex_jstruc_slice2 = list.copy(list(f))

# JESteps test knowns


ex_fillings_line1 = "FillingsUpdate: mu: +0.714406772 \
nElectrons: 64.000000 magneticMoment: [ Abs: 0.00578 Tot: -0.00141 ]"
ex_fillings_line1_known = {
"mu": 0.714406772 * Ha_to_eV,
"nelectrons": 64.0,
"abs_magneticmoment": 0.00578,
"tot_magneticmoment": -0.00141,
}

ex_fillings_line2 = "FillingsUpdate: mu: +0.814406772 \
nElectrons: 60.000000 magneticMoment: [ Abs: 0.0578 Tot: -0.0141 ]"
ex_fillings_line2_known = {
"mu": 0.814406772 * Ha_to_eV,
"nelectrons": 60.0,
"abs_magneticmoment": 0.0578,
"tot_magneticmoment": -0.0141,
}

ex_subspace_line1 = "SubspaceRotationAdjust: set factor to 0.229"
ex_subspace_line1_known = {"subspacerotationadjust": 0.229}

ex_subspace_line2 = "SubspaceRotationAdjust: set factor to 0.329"
ex_subspace_line2_known = {"subspacerotationadjust": 0.329}

ex_iter_line1 = "ElecMinimize: Iter: 6 F: -246.531038317370076\
|grad|_K: 6.157e-08 alpha: 5.534e-01 linmin: -4.478e-06\
t[s]: 248.68"
ex_iter_line1_known = {
"nstep": 6,
"e": -246.531038317370076 * Ha_to_eV,
"grad_k": 6.157e-08,
"alpha": 5.534e-01,
"linmin": -4.478e-06,
"t_s": 248.68,
}

ex_iter_line2 = "ElecMinimize: Iter: 7 F: -240.531038317370076\
|grad|_K: 6.157e-07 alpha: 5.534e-02 linmin: -5.478e-06\
t[s]: 48.68"
ex_iter_line2_known = {
"nstep": 7,
"e": -240.531038317370076 * Ha_to_eV,
"grad_k": 6.157e-07,
"alpha": 5.534e-02,
"linmin": -5.478e-06,
"t_s": 48.68,
}


ex_jstep_lines1 = [ex_fillings_line1, ex_subspace_line1, ex_iter_line1]
ex_jstep_lines2 = [ex_fillings_line2, ex_subspace_line2, ex_iter_line2]
ex_jstep_known1 = {}
for known1 in [ex_fillings_line1_known, ex_iter_line1_known, ex_subspace_line1_known]:
ex_jstep_known1.update(known1)
ex_jstep_known2 = {}
for known2 in [ex_fillings_line2_known, ex_iter_line2_known, ex_subspace_line2_known]:
ex_jstep_known2.update(known2)
4 changes: 1 addition & 3 deletions tests/io/jdftx/test_jdftxinfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ def test_JDFTXInfile_set_values(val_key: str, val: Any):
@pytest.mark.parametrize(
("val_key", "val"),
[
# ("fluid-solvent", "H2O 0.5"), # Causes issues with the list representation
("fluid-solvent", "H2O"),
("dump", "End DOS"),
("dump", "End DOS BandEigs"),
Expand Down Expand Up @@ -127,9 +126,8 @@ def test_JDFTXInfile_expected_exceptions():
value = {"blockSize": 1, "nOuterVxx": "barbie"}
err_str = str(f"The {tag} tag with value:\n{value}\ncould not be fixed!")
with pytest.raises(ValueError, match=re.escape(err_str)):
# Cannot set item without calling validate_tags
# Implicitly tests validate_tags
jif[tag] = value
# jif.validate_tags()
jif2 = jif.copy()
jif2.update({tag: value})
with pytest.raises(ValueError, match=re.escape(err_str)):
Expand Down
120 changes: 0 additions & 120 deletions tests/io/jdftx/test_jdftxoutfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,123 +53,3 @@ def test_JDFTXOutfile_fromfile(filename: Path, known: dict):
)
def test_JDFTXOutfile_fromfile_simple(filename: Path, known: dict):
jdftxoutfile_fromfile_matches_known_simple(filename, known)


empty_slice_exception_varnames = [
"prefix",
"jstrucs",
"jsettings_fluid",
"jsettings_electronic",
"jsettings_lattice",
"jsettings_ionic",
"xc_func",
"lattice_initial",
"lattice_final",
"lattice",
"a",
"b",
"c",
"fftgrid",
"geom_opt",
"geom_opt_type",
"efermi",
"egap",
"emin",
"emax",
"homo",
"lumo",
"homo_filling",
"lumo_filling",
"is_metal",
"etype",
"broadening_type",
"broadening",
"kgrid",
"truncation_type",
"truncation_radius",
"pwcut",
"rhocut",
"pp_type",
"total_electrons",
"semicore_electrons",
"valence_electrons",
"total_electrons_uncharged",
"semicore_electrons_uncharged",
"valence_electrons_uncharged",
"nbands",
"atom_elements",
"atom_elements_int",
"atom_types",
"spintype",
"nspin",
"nat",
"atom_coords_initial",
"atom_coords_final",
"atom_coords",
"has_solvation",
"fluid",
"is_gc",
"eopt_type",
"elecmindata",
"stress",
"strain",
"nstep",
"e",
"grad_k",
"alpha",
"linmin",
"nelectrons",
"abs_magneticmoment",
"tot_magneticmoment",
"mu",
"elec_nstep",
"elec_e",
"elec_grad_k",
"elec_alpha",
"elec_linmin",
]


# @pytest.mark.parametrize(
# ("dummy_filename", "none_exceptions"),
# [
# (
# ex_files_dir / Path("example_sp.out"),
# [
# "nstep",
# "stress",
# "strain",
# "linmin",
# "alpha",
# "truncation_radius",
# "grad_k",
# "abs_magneticmoment",
# "tot_magneticmoment",
# "elec_grad_k",
# "elec_alpha",
# "elec_linmin",
# ],
# )
# ],
# )
# def test_JDFTXOutfile_expected_exceptions_empty_slices(
# dummy_filename: PathLike,
# none_exceptions: list[str],
# ):
# for var in empty_slice_exception_varnames:
# expected_exceptions_empty_slices_test_varname(dummy_filename, var, none_exceptions)


# def expected_exceptions_empty_slices_test_varname(jout_filename: str, varname: str, none_exceptions: list[str]):
# jout = JDFTXOutfile.from_file(jout_filename)
# # First test that the attribute can be called
# val = getattr(jout, varname)
# # Next test it was properly called, or that its None if None is expected (but not both)
# v1 = bool(val is not None)
# v2 = bool(varname in none_exceptions)
# assert v1 != v2
# # assert bool(val is not None) != bool(val in none_exceptions)
# # Next test the error when slices is empty
# jout.slices = []
# with pytest.raises(AttributeError):
# getattr(jout, varname)
48 changes: 2 additions & 46 deletions tests/io/jdftx/test_jdftxoutfileslice.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,46 +12,9 @@
from pymatgen.io.jdftx.jdftxoutfileslice import JDFTXOutfileSlice
from pymatgen.util.testing import TEST_FILES_DIR

ex_files_dir = Path(TEST_FILES_DIR) / "io" / "jdftx" / "example_files"
from .conftest import ex_outfileslice1 as ex_slice1

ex_slice1_fname = ex_files_dir / "ex_out_slice_latmin"
ex_slice2_fname = ex_files_dir / "ex_out_slice_ionmin"
with open(ex_slice1_fname) as f:
ex_slice1 = list.copy(list(f))
with open(ex_slice2_fname) as f:
ex_slice2 = list.copy(list(f))


# @pytest.mark.parametrize(
# ("out_slice", "varname"),
# [
# (ex_slice1, "structure"),
# (ex_slice1, "eopt_type"),
# (ex_slice1, "elecmindata"),
# (ex_slice1, "stress"),
# (ex_slice1, "strain"),
# (ex_slice1, "nstep"),
# (ex_slice1, "e"),
# (ex_slice1, "grad_k"),
# (ex_slice1, "alpha"),
# (ex_slice1, "linmin"),
# (ex_slice1, "abs_magneticmoment"),
# (ex_slice1, "tot_magneticmoment"),
# (ex_slice1, "mu"),
# (ex_slice1, "elec_nstep"),
# (ex_slice1, "elec_e"),
# (ex_slice1, "elec_grad_k"),
# (ex_slice1, "elec_alpha"),
# (ex_slice1, "elec_linmin"),
# (ex_slice1, "nelectrons"),
# ],
# )
# def test_jdftxoutfileslice_has_1layer_jstrucs_freakout(out_slice: list[str], varname: str):
# joutslice = JDFTXOutfileSlice.from_out_slice(out_slice)
# getattr(joutslice, varname) # No freakout here
# joutslice.jstrucs = None
# with pytest.raises(AttributeError):
# getattr(joutslice, varname) # Freakout here
ex_files_dir = Path(TEST_FILES_DIR) / "io" / "jdftx" / "example_files"


def test_jdftxoutfileslice_stringify():
Expand All @@ -71,7 +34,6 @@ def test_jdftxoutfileslice_trajectory():
traj = joutslice.trajectory
assert isinstance(traj, Trajectory)
del joutslice.jsettings_lattice.params["niterations"]
# joutslice.jsettings_lattice.params["niterations"] = None
with pytest.raises(ValueError, match=re.escape("Unknown issue due to partial initialization of settings objects.")):
traj = joutslice.trajectory

Expand All @@ -91,8 +53,6 @@ def test_get_broadeningvars():

def test_get_truncationvars():
joutslice = JDFTXOutfileSlice.from_out_slice(ex_slice1)
# with pytest.raises(ValueError, match="No truncation type found in out file."):
# joutslice.get_truncationvars([])
joutslice.is_bgw = True
with pytest.raises(ValueError, match="BGW slab Coulomb truncation must be along z!"):
joutslice.get_truncationvars(["coulomb-interaction Slab 010"])
Expand Down Expand Up @@ -131,17 +91,13 @@ def test_get_eigstats_varsdict():

def test_get_pp_type():
joutslice = JDFTXOutfileSlice.from_out_slice(ex_slice1)
# with pytest.raises(ValueError, match="Could not determine pseudopotential type from file name root/PAW"):
# joutslice.get_pp_type(["Reading pseudopotential file root/PAW:"])
assert joutslice.get_pp_type(["Reading pseudopotential file root/PAW:"]) is None
assert joutslice.get_pp_type(["Reading pseudopotential file not_SG15/GBRV"]) == "GBRV"
assert joutslice.get_pp_type(["Reading pseudopotential file not_GBRV/SG15"]) == "SG15"


def test_set_pseudo_vars_t1():
joutslice = JDFTXOutfileSlice.from_out_slice(ex_slice1)
str(joutslice)
repr(joutslice)
# Just need more bound sets than there are atom types
text = [
"Reading pseudopotential file not_SG15/GBRV",
Expand Down
Loading

0 comments on commit b6d183c

Please sign in to comment.