Skip to content

Commit

Permalink
fix test + more renames
Browse files Browse the repository at this point in the history
  • Loading branch information
janosh committed Mar 27, 2024
1 parent 1bf618d commit b1e6160
Show file tree
Hide file tree
Showing 16 changed files with 124 additions and 124 deletions.
8 changes: 4 additions & 4 deletions tests/analysis/elasticity/test_elastic.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,11 +335,11 @@ def test_get_effective_ecs(self):
# Ensure zero strain is same as SOEC
test_zero = self.exp_cu.get_effective_ecs(np.zeros((3, 3)))
assert_allclose(test_zero, self.exp_cu[0])
s = np.zeros((3, 3))
s[0, 0] = 0.02
test_2percent = self.exp_cu.get_effective_ecs(s)
strain = np.zeros((3, 3))
strain[0, 0] = 0.02
test_2percent = self.exp_cu.get_effective_ecs(strain)
diff = test_2percent - test_zero
assert_allclose(self.exp_cu[1].einsum_sequence([s]), diff)
assert_allclose(self.exp_cu[1].einsum_sequence([strain]), diff)

def test_get_strain_from_stress(self):
strain = Strain.from_voigt([0.05, 0, 0, 0, 0, 0])
Expand Down
10 changes: 5 additions & 5 deletions tests/analysis/structure_prediction/test_substitutor.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,19 @@ def get_table():

class TestSubstitutor(PymatgenTest):
def setUp(self):
self.s = Substitutor(threshold=1e-3, lambda_table=get_table(), alpha=-5.0)
self.substitutor = Substitutor(threshold=1e-3, lambda_table=get_table(), alpha=-5.0)

def test_substitutor(self):
s_list = [Species("O", -2), Species("Li", 1)]
subs = self.s.pred_from_list(s_list)
subs = self.substitutor.pred_from_list(s_list)
assert len(subs) == 4, "incorrect number of substitutions"
comp = Composition({"O2-": 1, "Li1+": 2})
subs = self.s.pred_from_comp(comp)
subs = self.substitutor.pred_from_comp(comp)
assert len(subs) == 4, "incorrect number of substitutions"

structures = [{"structure": PymatgenTest.get_structure("Li2O"), "id": "pmgtest"}]
subs = self.s.pred_from_structures(["Na+", "O2-"], structures)
subs = self.substitutor.pred_from_structures(["Na+", "O2-"], structures)
assert subs[0].formula == "Na2 O1"

def test_as_dict(self):
Substitutor.from_dict(self.s.as_dict())
Substitutor.from_dict(self.substitutor.as_dict())
4 changes: 2 additions & 2 deletions tests/analysis/test_dimensionality.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,8 @@ def test_zero_d_to_molecule_graph(self):
zero_d_graph_to_molecule_graph(self.graphite, comp_graphs[0])

# test for a troublesome structure
s = loadfn(f"{TEST_FILES_DIR}/PH7CN3O3F.json.gz")
bs = CrystalNN().get_bonded_structure(s)
struct = loadfn(f"{TEST_FILES_DIR}/PH7CN3O3F.json.gz")
bs = CrystalNN().get_bonded_structure(struct)
comp_graphs = [bs.graph.subgraph(c) for c in nx.weakly_connected_components(bs.graph)]
mol_graph = zero_d_graph_to_molecule_graph(bs, comp_graphs[0])
assert len(mol_graph.molecule) == 12
Expand Down
6 changes: 3 additions & 3 deletions tests/analysis/test_ewald.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,11 +109,11 @@ def test_site(self):
"""Test that uses an uncharged structure."""
filepath = f"{VASP_IN_DIR}/POSCAR"
struct = Structure.from_file(filepath)
s = struct.copy()
s.add_oxidation_state_by_element({"Li": 1, "Fe": 3, "P": 5, "O": -2})
struct = struct.copy()
struct.add_oxidation_state_by_element({"Li": 1, "Fe": 3, "P": 5, "O": -2})

# Comparison to LAMMPS result
ham = EwaldSummation(s, compute_forces=True)
ham = EwaldSummation(struct, compute_forces=True)
assert approx(ham.total_energy, abs=1e-3) == -1226.3335
assert approx(ham.get_site_energy(0), abs=1e-3) == -45.8338
assert approx(ham.get_site_energy(8), abs=1e-3) == -27.2978
8 changes: 4 additions & 4 deletions tests/analysis/test_structure_analyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,17 @@

class TestVoronoiAnalyzer(PymatgenTest):
def setUp(self):
self.ss = Xdatcar(f"{VASP_OUT_DIR}/XDATCAR.MD").structures
self.s = self.ss[1]
self.structs = Xdatcar(f"{VASP_OUT_DIR}/XDATCAR.MD").structures
self.struct = self.structs[1]
self.va = VoronoiAnalyzer(cutoff=4)

def test_analyze(self):
# Check for the Voronoi index of site i in Structure
single_structure = self.va.analyze(self.s, n=5)
single_structure = self.va.analyze(self.struct, n=5)
assert single_structure.view() in np.array([4, 3, 3, 4, 2, 2, 1, 0]).view(), "Cannot find the right polyhedron."
# Check for the presence of a Voronoi index and its frequency in
# a ensemble (list) of Structures
ensemble = self.va.analyze_structures(self.ss, step_freq=2, most_frequent_polyhedra=10)
ensemble = self.va.analyze_structures(self.structs, step_freq=2, most_frequent_polyhedra=10)
assert ("[1 3 4 7 1 0 0 0]", 3) in ensemble, "Cannot find the right polyhedron in ensemble."


Expand Down
30 changes: 15 additions & 15 deletions tests/analysis/test_structure_matcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,27 +116,27 @@ def test_cart_dists(self):
with pytest.raises(ValueError, match="mask has incorrect shape"):
sm._cart_dists(s1, s2, lattice, mask.T, n1)

d, ft, s = sm._cart_dists(s1, s2, lattice, mask, n1)
assert_allclose(d, [0])
assert_allclose(ft, [-0.01, -0.02, -0.03])
assert_allclose(s, [1])
distances, trac_trans_vec, solution = sm._cart_dists(s1, s2, lattice, mask, n1)
assert_allclose(distances, [0])
assert_allclose(trac_trans_vec, [-0.01, -0.02, -0.03])
assert_allclose(solution, [1])

# check that masking best value works
d, ft, s = sm._cart_dists(s1, s2, lattice, mask2, n1)
assert_allclose(d, [0])
assert_allclose(ft, [0.02, 0.03, 0.04])
assert_allclose(s, [0])
distances, trac_trans_vec, solution = sm._cart_dists(s1, s2, lattice, mask2, n1)
assert_allclose(distances, [0])
assert_allclose(trac_trans_vec, [0.02, 0.03, 0.04])
assert_allclose(solution, [0])

# check that averaging of translation is done properly
d, ft, s = sm._cart_dists(s1, s3, lattice, mask3, n1)
assert_allclose(d, [0.08093341] * 2)
assert_allclose(ft, [0.01, 0.025, 0.035])
assert_allclose(s, [1, 0])
distances, trac_trans_vec, solution = sm._cart_dists(s1, s3, lattice, mask3, n1)
assert_allclose(distances, [0.08093341] * 2)
assert_allclose(trac_trans_vec, [0.01, 0.025, 0.035])
assert_allclose(solution, [1, 0])

# check distances are large when mask allows no 'real' mapping
d, ft, s = sm._cart_dists(s1, s4, lattice, mask4, n1)
assert np.min(d) > 1e8
assert np.min(ft) > 1e8
distances, trac_trans_vec, solution = sm._cart_dists(s1, s4, lattice, mask4, n1)
assert np.min(distances) > 1e8
assert np.min(trac_trans_vec) > 1e8

def test_get_mask(self):
sm = StructureMatcher(comparator=ElementComparator())
Expand Down
14 changes: 7 additions & 7 deletions tests/analysis/test_surface_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,8 @@ def test_cleaned_up_slab(self):
for hkl in val:
for clean in self.metals_O_entry_dict[el][hkl]:
for ads in self.metals_O_entry_dict[el][hkl][clean]:
s = ads.cleaned_up_slab
assert s.composition.reduced_composition == clean.composition.reduced_composition
slab_clean = ads.cleaned_up_slab
assert slab_clean.composition.reduced_composition == clean.composition.reduced_composition


class TestSurfaceEnergyPlotter(PymatgenTest):
Expand Down Expand Up @@ -320,26 +320,26 @@ def setUp(self):
def test_stability_at_r(self):
# Check that we have a different polymorph that is
# stable below or above the equilibrium particle size
r = self.nanoscale_stability.solve_equilibrium_point(self.La_hcp_analyzer, self.La_fcc_analyzer) * 10
radius = self.nanoscale_stability.solve_equilibrium_point(self.La_hcp_analyzer, self.La_fcc_analyzer) * 10

# hcp phase of La particle should be the stable
# polymorph above the equilibrium radius
hcp_wulff = self.La_hcp_analyzer.wulff_from_chempot()
bulk = self.La_hcp_analyzer.ucell_entry
ghcp, _rhcp = self.nanoscale_stability.wulff_gform_and_r(hcp_wulff, bulk, r + 10, from_sphere_area=True)
ghcp, _rhcp = self.nanoscale_stability.wulff_gform_and_r(hcp_wulff, bulk, radius + 10, from_sphere_area=True)
fcc_wulff = self.La_fcc_analyzer.wulff_from_chempot()
bulk = self.La_fcc_analyzer.ucell_entry
gfcc, _rfcc = self.nanoscale_stability.wulff_gform_and_r(fcc_wulff, bulk, r + 10, from_sphere_area=True)
gfcc, _rfcc = self.nanoscale_stability.wulff_gform_and_r(fcc_wulff, bulk, radius + 10, from_sphere_area=True)
assert gfcc > ghcp

# fcc phase of La particle should be the stable
# polymorph below the equilibrium radius
hcp_wulff = self.La_hcp_analyzer.wulff_from_chempot()
bulk = self.La_hcp_analyzer.ucell_entry
ghcp, _rhcp = self.nanoscale_stability.wulff_gform_and_r(hcp_wulff, bulk, r - 10, from_sphere_area=True)
ghcp, _rhcp = self.nanoscale_stability.wulff_gform_and_r(hcp_wulff, bulk, radius - 10, from_sphere_area=True)
fcc_wulff = self.La_fcc_analyzer.wulff_from_chempot()
bulk = self.La_fcc_analyzer.ucell_entry
gfcc, _rfcc = self.nanoscale_stability.wulff_gform_and_r(fcc_wulff, bulk, r - 10, from_sphere_area=True)
gfcc, _rfcc = self.nanoscale_stability.wulff_gform_and_r(fcc_wulff, bulk, radius - 10, from_sphere_area=True)
assert gfcc < ghcp

def test_scaled_wulff(self):
Expand Down
14 changes: 7 additions & 7 deletions tests/command_line/test_enumlib_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ def test_init(self):
adaptor.run()
structures = adaptor.structures
assert len(structures) == 86
for s in structures:
assert s.composition.get_atomic_fraction(Element("Li")) == approx(0.5 / 6.5)
for struct_trafo in structures:
assert struct_trafo.composition.get_atomic_fraction(Element("Li")) == approx(0.5 / 6.5)
adaptor = EnumlibAdaptor(sub_trans.apply_transformation(struct), 1, 2, refine_structure=True)
adaptor.run()
structures = adaptor.structures
Expand All @@ -40,8 +40,8 @@ def test_init(self):
adaptor.run()
structures = adaptor.structures
assert len(structures) == 1
for s in structures:
assert s.composition.get_atomic_fraction(Element("Li")) == approx(0.25 / 6.25)
for struct_trafo in structures:
assert struct_trafo.composition.get_atomic_fraction(Element("Li")) == approx(0.25 / 6.25)

# Make sure it works for completely disordered structures.
struct = Structure(np.eye(3) * 10, [{"Fe": 0.5}], [[0, 0, 0]])
Expand All @@ -52,11 +52,11 @@ def test_init(self):
# Make sure it works properly when symmetry is broken by ordered sites.
struct = self.get_structure("LiFePO4")
sub_trans = SubstitutionTransformation({"Li": {"Li": 0.25}})
s = sub_trans.apply_transformation(struct)
struct_trafo = sub_trans.apply_transformation(struct)
# REmove some ordered sites to break symmetry.
remove_trans = RemoveSitesTransformation([4, 7])
s = remove_trans.apply_transformation(s)
adaptor = EnumlibAdaptor(s, 1, 1, enum_precision_parameter=0.01)
struct_trafo = remove_trans.apply_transformation(struct_trafo)
adaptor = EnumlibAdaptor(struct_trafo, 1, 1, enum_precision_parameter=0.01)
adaptor.run()
structures = adaptor.structures
assert len(structures) == 4
Expand Down
11 changes: 6 additions & 5 deletions tests/core/test_periodic_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -453,8 +453,8 @@ def test_get_crystal_field_spin(self):
with pytest.raises(ValueError, match="Invalid coordination or spin config"):
Species("Fe", 2).get_crystal_field_spin("hex")

s = Species("Co", 3).get_crystal_field_spin("tet", spin_config="low")
assert s == 2
spin = Species("Co", 3).get_crystal_field_spin("tet", spin_config="low")
assert spin == 2

def test_get_nmr_mom(self):
assert Species("H").get_nmr_quadrupole_moment() == 2.860
Expand Down Expand Up @@ -575,17 +575,18 @@ def test_pickle(self):
assert el1 == pickle.loads(pickled)

def test_sort(self):
r = sorted([Element.Fe, DummySpecies("X")])
assert r == [DummySpecies("X"), Element.Fe]
Fe, X = Element.Fe, DummySpecies("X")
assert sorted([Fe, X]) == [X, Fe]
assert DummySpecies("X", 3) < DummySpecies("X", 4)

sp = Species("Fe", 2, spin=5)
with pytest.raises(AttributeError) as exc:
sp.spin = 6

# for some reason different message on Windows and Mac. on Linux: 'can't set attribute'
assert "can't set attribute" in str(exc.value) or "property 'spin' of 'Species' object has no setter" in str(
exc.value
) # 'can't set attribute' on Linux, for some reason different message on Windows and Mac
)
assert sp.spin == 5


Expand Down
2 changes: 1 addition & 1 deletion tests/core/test_units.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ def func5():
def test_compound_operations(self):
earth_acc = 9.81 * Length(1, "m") / (Time(1, "s") ** 2)
e_pot = Mass(1, "kg") * earth_acc * Length(1, "m")
assert str(e_pot) == "10.0 N m"
assert str(e_pot) == "9.81 N m"
form_e = FloatWithUnit(10, unit="kJ mol^-1").to("eV atom^-1")
assert form_e == approx(0.103642691905)
assert str(form_e.unit) == "eV atom^-1"
Expand Down
28 changes: 14 additions & 14 deletions tests/io/cp2k/test_inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,16 +149,16 @@ def setUp(self):
self.ci = Cp2kInput.from_file(f"{TEST_FILES_DIR}/cp2k/cp2k.inp")

def test_basic_sections(self):
s = """
cp2k_input_str = """
&GLOBAL
RUN_TYPE ENERGY
PROJECT_NAME CP2K ! default name
&END
"""
ci = Cp2kInput.from_str(s)
assert ci["GLOBAL"]["RUN_TYPE"] == Keyword("RUN_TYPE", "energy")
assert ci["GLOBAL"]["PROJECT_NAME"].description == "default name"
self.assert_msonable(ci)
cp2k_input = Cp2kInput.from_str(cp2k_input_str)
assert cp2k_input["GLOBAL"]["RUN_TYPE"] == Keyword("RUN_TYPE", "energy")
assert cp2k_input["GLOBAL"]["PROJECT_NAME"].description == "default name"
self.assert_msonable(cp2k_input)

def test_sectionlist(self):
s1 = Section("TEST")
Expand Down Expand Up @@ -236,19 +236,19 @@ def test_preprocessor(self):
assert self.ci["FORCE_EVAL"]["DFT"]["SCF"]["MAX_SCF"] == Keyword("MAX_SCF", 1)

def test_mongo(self):
s = """
cp2k_input_str = """
&GLOBAL
RUN_TYPE ENERGY
PROJECT_NAME CP2K ! default name
&END
"""
s = Cp2kInput.from_str(s)
s.inc({"GLOBAL": {"TEST": 1}})
assert s["global"]["test"] == Keyword("TEST", 1)
cp2k_input = Cp2kInput.from_str(cp2k_input_str)
cp2k_input.inc({"GLOBAL": {"TEST": 1}})
assert cp2k_input["global"]["test"] == Keyword("TEST", 1)

s.unset({"GLOBAL": "RUN_TYPE"})
assert "RUN_TYPE" not in s["global"].keywords
cp2k_input.unset({"GLOBAL": "RUN_TYPE"})
assert "RUN_TYPE" not in cp2k_input["global"].keywords

s.set({"GLOBAL": {"SUBSEC": {"TEST2": 2}, "SUBSEC2": {"Test2": 1}}})
assert s.check("global/SUBSEC")
assert s.check("global/subsec2")
cp2k_input.set({"GLOBAL": {"SUBSEC": {"TEST2": 2}, "SUBSEC2": {"Test2": 1}}})
assert cp2k_input.check("global/SUBSEC")
assert cp2k_input.check("global/subsec2")
3 changes: 1 addition & 2 deletions tests/io/feff/test_sets.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,7 @@ def test_get_header(self):
if idx < 9:
assert line == ref[idx]
else:
s = " ".join(line.split()[2:])
assert s in last4
assert " ".join(line.split()[2:]) in last4

def test_get_feff_tags(self):
tags = self.mp_xanes.tags.as_dict()
Expand Down
4 changes: 2 additions & 2 deletions tests/io/vasp/test_inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -644,7 +644,7 @@ def test_write(self):
assert incar == self.incar

def test_get_str(self):
s = self.incar.get_str(pretty=True, sort_keys=True)
incar_str = self.incar.get_str(pretty=True, sort_keys=True)
expected = """ALGO = Damped
EDIFF = 0.0001
ENCUT = 500
Expand Down Expand Up @@ -673,7 +673,7 @@ def test_get_str(self):
SIGMA = 0.05
SYSTEM = Id=[0] dblock_code=[97763-icsd] formula=[li mn (p o4)] sg_name=[p n m a]
TIME = 0.4"""
assert s == expected
assert incar_str == expected

def test_lsorbit_magmom(self):
magmom1 = [[0.0, 0.0, 3.0], [0, 1, 0], [2, 1, 2]]
Expand Down

0 comments on commit b1e6160

Please sign in to comment.