From 6c508c0c0032a95d02a716238a9ab2ff6f68471d Mon Sep 17 00:00:00 2001 From: Janosh Riebesell Date: Sat, 14 Oct 2023 12:15:19 -0700 Subject: [PATCH] simplify Poscar.from_file().structure to Structure.from_file() --- pymatgen/analysis/surface_analysis.py | 10 ++-- pymatgen/analysis/transition_state.py | 7 +-- tests/analysis/test_ewald.py | 10 ++-- tests/analysis/test_structure_analyzer.py | 13 ++--- tests/command_line/test_gulp_caller.py | 7 +-- tests/core/test_trajectory.py | 4 +- tests/io/test_ase.py | 13 +---- tests/io/test_cif.py | 16 +++---- tests/io/test_cssr.py | 4 +- tests/io/test_jarvis.py | 21 +++++---- tests/io/test_xr.py | 5 +- tests/io/test_xyz.py | 5 +- tests/io/test_zeopp.py | 26 ++++------ tests/io/vasp/test_inputs.py | 47 +++++++++---------- tests/io/vasp/test_sets.py | 43 +++++++---------- tests/symmetry/test_analyzer.py | 9 ++-- .../test_advanced_transformations.py | 16 ++----- .../test_standard_transformations.py | 10 ++-- 18 files changed, 102 insertions(+), 164 deletions(-) diff --git a/pymatgen/analysis/surface_analysis.py b/pymatgen/analysis/surface_analysis.py index 636b26abd17..fb802c3abfc 100644 --- a/pymatgen/analysis/surface_analysis.py +++ b/pymatgen/analysis/surface_analysis.py @@ -38,7 +38,6 @@ import itertools import random import warnings -from typing import TYPE_CHECKING import matplotlib.pyplot as plt import numpy as np @@ -46,17 +45,15 @@ from sympy.solvers import linsolve, solve from pymatgen.analysis.wulff import WulffShape +from pymatgen.core import Structure from pymatgen.core.composition import Composition from pymatgen.core.surface import get_slab_regions from pymatgen.entries.computed_entries import ComputedStructureEntry -from pymatgen.io.vasp.outputs import Locpot, Outcar, Poscar +from pymatgen.io.vasp.outputs import Locpot, Outcar from pymatgen.symmetry.analyzer import SpacegroupAnalyzer from pymatgen.util.due import Doi, due from pymatgen.util.plotting import pretty_plot -if TYPE_CHECKING: - from pymatgen.core import Structure - EV_PER_ANG2_TO_JOULES_PER_M2 = 16.0217656 __author__ = "Richard Tran" @@ -1578,11 +1575,10 @@ def from_files(cls, poscar_filename, locpot_filename, outcar_filename, shift=0, Returns: WorkFunctionAnalyzer: A WorkFunctionAnalyzer instance. """ - poscar = Poscar.from_file(poscar_filename) locpot = Locpot.from_file(locpot_filename) outcar = Outcar(outcar_filename) return cls( - poscar.structure, + Structure.from_file(poscar_filename), locpot.get_average_along_axis(2), outcar.efermi, shift=shift, diff --git a/pymatgen/analysis/transition_state.py b/pymatgen/analysis/transition_state.py index 9075e35411a..5009ae4308b 100644 --- a/pymatgen/analysis/transition_state.py +++ b/pymatgen/analysis/transition_state.py @@ -17,7 +17,8 @@ from scipy.interpolate import CubicSpline from pymatgen.analysis.structure_matcher import StructureMatcher -from pymatgen.io.vasp import Outcar, Poscar +from pymatgen.core import Structure +from pymatgen.io.vasp import Outcar from pymatgen.util.plotting import pretty_plot @@ -267,10 +268,10 @@ def from_dir(cls, root_dir, relaxation_dirs=None, **kwargs): break else: raise ValueError(f"OUTCAR cannot be found for terminal point {d}") - structures.append(Poscar.from_file(poscar[0]).structure) + structures.append(Structure.from_file(poscar[0])) else: outcars.append(Outcar(outcar[0])) - structures.append(Poscar.from_file(contcar[0]).structure) + structures.append(Structure.from_file(contcar[0])) return NEBAnalysis.from_outcars(outcars, structures, **kwargs) def as_dict(self): diff --git a/tests/analysis/test_ewald.py b/tests/analysis/test_ewald.py index b850a12239c..d316fc1bee1 100644 --- a/tests/analysis/test_ewald.py +++ b/tests/analysis/test_ewald.py @@ -7,15 +7,14 @@ from pytest import approx from pymatgen.analysis.ewald import EwaldMinimizer, EwaldSummation -from pymatgen.io.vasp.inputs import Poscar +from pymatgen.core.structure import Structure from pymatgen.util.testing import TEST_FILES_DIR class TestEwaldSummation(unittest.TestCase): def setUp(self): filepath = f"{TEST_FILES_DIR}/POSCAR" - poscar = Poscar.from_file(filepath, check_for_POTCAR=False) - self.original_struct = poscar.structure + self.original_struct = Structure.from_file(filepath) self.struct = self.original_struct.copy() self.struct.add_oxidation_state_by_element({"Li": 1, "Fe": 2, "P": 5, "O": -2}) @@ -109,9 +108,8 @@ def test_init(self): def test_site(self): """Test that uses an uncharged structure.""" filepath = f"{TEST_FILES_DIR}/POSCAR" - p = Poscar.from_file(filepath, check_for_POTCAR=False) - original_s = p.structure - s = original_s.copy() + struct = Structure.from_file(filepath) + s = struct.copy() s.add_oxidation_state_by_element({"Li": 1, "Fe": 3, "P": 5, "O": -2}) # Comparison to LAMMPS result diff --git a/tests/analysis/test_structure_analyzer.py b/tests/analysis/test_structure_analyzer.py index 9d9eafc7afd..a2c28baf452 100644 --- a/tests/analysis/test_structure_analyzer.py +++ b/tests/analysis/test_structure_analyzer.py @@ -19,7 +19,6 @@ from pymatgen.core.lattice import Lattice from pymatgen.core.periodic_table import Element from pymatgen.core.structure import Structure -from pymatgen.io.vasp.inputs import Poscar from pymatgen.io.vasp.outputs import Xdatcar from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest @@ -42,16 +41,14 @@ def test_analyze(self): class TestRelaxationAnalyzer(unittest.TestCase): def setUp(self): - p = Poscar.from_file(f"{TEST_FILES_DIR}/POSCAR.Li2O", check_for_POTCAR=False) - s1 = p.structure - p = Poscar.from_file(f"{TEST_FILES_DIR}/CONTCAR.Li2O", check_for_POTCAR=False) - s2 = p.structure + s1 = Structure.from_file(f"{TEST_FILES_DIR}/POSCAR.Li2O") + s2 = Structure.from_file(f"{TEST_FILES_DIR}/CONTCAR.Li2O") self.analyzer = RelaxationAnalyzer(s1, s2) def test_vol_and_para_changes(self): - for v in self.analyzer.get_percentage_lattice_parameter_changes().values(): - assert approx(v) == -0.0092040921155279731 - latt_change = v + for val in self.analyzer.get_percentage_lattice_parameter_changes().values(): + assert approx(val) == -0.0092040921155279731 + latt_change = val vol_change = self.analyzer.get_percentage_volume_change() assert approx(vol_change) == -0.0273589101391 # This is a simple cubic cell, so the latt and vol change are simply diff --git a/tests/command_line/test_gulp_caller.py b/tests/command_line/test_gulp_caller.py index 03f7b659310..7098f7c6fbb 100644 --- a/tests/command_line/test_gulp_caller.py +++ b/tests/command_line/test_gulp_caller.py @@ -24,7 +24,6 @@ get_energy_tersoff, ) from pymatgen.core.structure import Structure -from pymatgen.io.vasp.inputs import Poscar from pymatgen.util.testing import TEST_FILES_DIR gulp_present = which("gulp") and os.getenv("GULP_LIB") and ("win" not in sys.platform) @@ -100,8 +99,7 @@ def test_decimal(self): @unittest.skipIf(not gulp_present, "gulp not present.") class TestGulpIO(unittest.TestCase): def setUp(self): - p = Poscar.from_file(f"{TEST_FILES_DIR}/POSCAR.Al12O18", check_for_POTCAR=False) - self.structure = p.structure + self.structure = Structure.from_file(f"{TEST_FILES_DIR}/POSCAR.Al12O18") self.gio = GulpIO() def test_keyword_line_with_correct_keywords(self): @@ -282,8 +280,7 @@ def setUp(self): self.val_dict = dict(zip(el, val)) def test_get_energy_tersoff(self): - p = Poscar.from_file(f"{TEST_FILES_DIR}/POSCAR.Al12O18", check_for_POTCAR=False) - structure = p.structure + structure = Structure.from_file(f"{TEST_FILES_DIR}/POSCAR.Al12O18") energy = get_energy_tersoff(structure) assert isinstance(energy, float) diff --git a/tests/core/test_trajectory.py b/tests/core/test_trajectory.py index fedca900561..2f7291a25ab 100644 --- a/tests/core/test_trajectory.py +++ b/tests/core/test_trajectory.py @@ -10,7 +10,6 @@ from pymatgen.core.structure import Molecule, Structure from pymatgen.core.trajectory import Trajectory from pymatgen.io.qchem.outputs import QCOutput -from pymatgen.io.vasp.inputs import Poscar from pymatgen.io.vasp.outputs import Xdatcar from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest @@ -418,8 +417,7 @@ def test_length(self): assert len(self.traj_mols) == len(self.molecules) def test_displacements(self): - poscar = Poscar.from_file(f"{TEST_FILES_DIR}/POSCAR") - structures = [poscar.structure] + structures = [Structure.from_file(f"{TEST_FILES_DIR}/POSCAR")] displacements = np.zeros((11, *np.shape(structures[-1].frac_coords))) for i in range(10): diff --git a/tests/io/test_ase.py b/tests/io/test_ase.py index e4746fc91b7..9cd6702c5af 100644 --- a/tests/io/test_ase.py +++ b/tests/io/test_ase.py @@ -9,15 +9,13 @@ from pymatgen.core import Composition, Lattice, Molecule, Structure from pymatgen.core.structure import StructureError from pymatgen.io.ase import AseAtomsAdaptor -from pymatgen.io.vasp.inputs import Poscar from pymatgen.util.testing import TEST_FILES_DIR -poscar = Poscar.from_file(TEST_FILES_DIR / "POSCAR") +structure = Structure.from_file(TEST_FILES_DIR / "POSCAR") ase = pytest.importorskip("ase") def test_get_atoms_from_structure(): - structure = poscar.structure atoms = AseAtomsAdaptor.get_atoms(structure) ase_composition = Composition(atoms.get_chemical_formula()) assert ase_composition == structure.composition @@ -30,7 +28,6 @@ def test_get_atoms_from_structure(): assert not atoms.has("initial_charges") assert atoms.calc is None - structure = poscar.structure prop = [3.14] * len(structure) structure.add_site_property("prop", prop) atoms = AseAtomsAdaptor.get_atoms(structure) @@ -38,20 +35,17 @@ def test_get_atoms_from_structure(): def test_get_atoms_from_structure_mags(): - structure = poscar.structure mags = [1.0] * len(structure) structure.add_site_property("final_magmom", mags) atoms = AseAtomsAdaptor.get_atoms(structure) assert not atoms.has("initial_magmoms") assert atoms.get_magnetic_moments().tolist() == mags - structure = poscar.structure initial_mags = [0.5] * len(structure) structure.add_site_property("magmom", initial_mags) atoms = AseAtomsAdaptor.get_atoms(structure) assert atoms.get_initial_magnetic_moments().tolist() == initial_mags - structure = poscar.structure mags = [1.0] * len(structure) structure.add_site_property("final_magmom", mags) initial_mags = [2.0] * len(structure) @@ -62,20 +56,17 @@ def test_get_atoms_from_structure_mags(): def test_get_atoms_from_structure_charge(): - structure = poscar.structure charges = [1.0] * len(structure) structure.add_site_property("final_charge", charges) atoms = AseAtomsAdaptor.get_atoms(structure) assert not atoms.has("initial_charges") assert atoms.get_charges().tolist() == charges - structure = poscar.structure charges = [0.5] * len(structure) structure.add_site_property("charge", charges) atoms = AseAtomsAdaptor.get_atoms(structure) assert atoms.get_initial_charges().tolist() == charges - structure = poscar.structure charges = [1.0] * len(structure) structure.add_site_property("final_charge", charges) initial_charges = [2.0] * len(structure) @@ -86,7 +77,6 @@ def test_get_atoms_from_structure_charge(): def test_get_atoms_from_structure_oxi_states(): - structure = poscar.structure oxi_states = [1.0] * len(structure) structure.add_oxidation_state_by_site(oxi_states) atoms = AseAtomsAdaptor.get_atoms(structure) @@ -94,7 +84,6 @@ def test_get_atoms_from_structure_oxi_states(): def test_get_atoms_from_structure_dyn(): - structure = poscar.structure structure.add_site_property("selective_dynamics", [[False] * 3] * len(structure)) atoms = AseAtomsAdaptor.get_atoms(structure) assert atoms.constraints[0].get_indices().tolist() == [atom.index for atom in atoms] diff --git a/tests/io/test_cif.py b/tests/io/test_cif.py index 6fd6f64824a..6cc5b151591 100644 --- a/tests/io/test_cif.py +++ b/tests/io/test_cif.py @@ -13,7 +13,6 @@ from pymatgen.core.structure import Structure from pymatgen.electronic_structure.core import Magmom from pymatgen.io.cif import CifBlock, CifParser, CifWriter -from pymatgen.io.vasp.inputs import Poscar from pymatgen.symmetry.structure import SymmetrizedStructure from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest @@ -421,8 +420,8 @@ def test_parse_symbol(self): def test_cif_writer(self): filepath = f"{TEST_FILES_DIR}/POSCAR" - poscar = Poscar.from_file(filepath) - writer = CifWriter(poscar.structure, symprec=0.01) + struct = Structure.from_file(filepath) + writer = CifWriter(struct, symprec=0.01) answer = """# generated using pymatgen data_FePO4 _symmetry_space_group_name_H-M Pnma @@ -466,13 +465,13 @@ def test_cif_writer(self): def test_symmetrized(self): filepath = f"{TEST_FILES_DIR}/POSCAR" - poscar = Poscar.from_file(filepath, check_for_POTCAR=False) - writer = CifWriter(poscar.structure, symprec=0.1) + struct = Structure.from_file(filepath) + writer = CifWriter(struct, symprec=0.1) cif = CifParser.from_str(str(writer)) m = StructureMatcher() - assert m.fit(cif.get_structures()[0], poscar.structure) + assert m.fit(cif.get_structures()[0], struct) # for l1, l2 in zip(str(writer).split("\n"), answer.split("\n")): # assert l1.strip() == l2.strip() @@ -716,11 +715,10 @@ def test_get_lattice_from_lattice_type(self): parser = CifParser.from_str(cif_structure) s_test = parser.get_structures(primitive=False)[0] filepath = f"{TEST_FILES_DIR}/POSCAR" - poscar = Poscar.from_file(filepath) - s_ref = poscar.structure + struct = Structure.from_file(filepath) sm = StructureMatcher(stol=0.05, ltol=0.01, angle_tol=0.1) - assert sm.fit(s_ref, s_test) + assert sm.fit(struct, s_test) def test_empty(self): # single line diff --git a/tests/io/test_cssr.py b/tests/io/test_cssr.py index 803b3baf75e..66ca301f998 100644 --- a/tests/io/test_cssr.py +++ b/tests/io/test_cssr.py @@ -6,7 +6,6 @@ from pymatgen.core.structure import Structure from pymatgen.io.cssr import Cssr -from pymatgen.io.vasp.inputs import Poscar from pymatgen.util.testing import TEST_FILES_DIR __author__ = "Shyue Ping Ong" @@ -20,8 +19,7 @@ class TestCssr(unittest.TestCase): def setUp(self): filepath = f"{TEST_FILES_DIR}/POSCAR" - p = Poscar.from_file(filepath) - self.cssr = Cssr(p.structure) + self.cssr = Cssr(Structure.from_file(filepath)) def test_str(self): expected_string = """10.4118 6.0672 4.7595 diff --git a/tests/io/test_jarvis.py b/tests/io/test_jarvis.py index 513657d2fc1..9cbf80c1dbf 100644 --- a/tests/io/test_jarvis.py +++ b/tests/io/test_jarvis.py @@ -2,23 +2,24 @@ import unittest -import pymatgen.io.jarvis as jio -from pymatgen.io.vasp.inputs import Poscar +from pymatgen.core import Structure +from pymatgen.io.jarvis import Atoms, JarvisAtomsAdaptor from pymatgen.util.testing import TEST_FILES_DIR +@unittest.skipIf(not Atoms, "JARVIS-tools not loaded.") class TestJarvisAtomsAdaptor(unittest.TestCase): - @unittest.skipIf(not jio.Atoms, "JARVIS-tools not loaded.") def test_get_atoms_from_structure(self): - structure = Poscar.from_file(f"{TEST_FILES_DIR}/POSCAR").structure - atoms = jio.JarvisAtomsAdaptor.get_atoms(structure) + struct = Structure.from_file(f"{TEST_FILES_DIR}/POSCAR") + atoms = JarvisAtomsAdaptor.get_atoms(struct) jarvis_composition = atoms.composition.reduced_formula - assert jarvis_composition == structure.composition.reduced_formula + assert jarvis_composition == struct.composition.reduced_formula assert atoms.lattice_mat is not None assert atoms.lattice_mat.any() - @unittest.skipIf(not jio.Atoms, "JARVIS-tools not loaded.") def test_get_structure(self): - structure = Poscar.from_file(f"{TEST_FILES_DIR}/POSCAR").structure - atoms = jio.JarvisAtomsAdaptor.get_atoms(structure) - assert jio.JarvisAtomsAdaptor.get_structure(atoms).composition.reduced_formula == "FePO4" + struct = Structure.from_file(f"{TEST_FILES_DIR}/POSCAR") + atoms = JarvisAtomsAdaptor.get_atoms(struct) + assert len(atoms.frac_coords) == len(struct) == 24 + round_trip = JarvisAtomsAdaptor.get_structure(atoms) + assert round_trip.formula == struct.formula == "Fe4 P4 O16" diff --git a/tests/io/test_xr.py b/tests/io/test_xr.py index 31c90e0cca9..f30ac37e4eb 100644 --- a/tests/io/test_xr.py +++ b/tests/io/test_xr.py @@ -3,7 +3,6 @@ import unittest from pymatgen.core.structure import Structure -from pymatgen.io.vasp.inputs import Poscar from pymatgen.io.xr import Xr from pymatgen.util.testing import TEST_FILES_DIR @@ -17,8 +16,8 @@ class TestXr(unittest.TestCase): def setUp(self): - p = Poscar.from_file(TEST_FILES_DIR / "POSCAR") - self.xr = Xr(p.structure) + struct = Structure.from_file(TEST_FILES_DIR / "POSCAR") + self.xr = Xr(struct) def test_str(self): expected_string = """pymatgen 10.4118 6.0672 4.7595 diff --git a/tests/io/test_xyz.py b/tests/io/test_xyz.py index 67982cda380..bab7462c2f1 100644 --- a/tests/io/test_xyz.py +++ b/tests/io/test_xyz.py @@ -7,8 +7,8 @@ import pytest from pytest import approx +from pymatgen.core import Structure from pymatgen.core.structure import Molecule -from pymatgen.io.vasp.inputs import Poscar from pymatgen.io.xyz import XYZ from pymatgen.util.testing import TEST_FILES_DIR @@ -136,8 +136,7 @@ def test_from_file(self): def test_init_from_structure(self): filepath = f"{TEST_FILES_DIR}/POSCAR" - poscar = Poscar.from_file(filepath) - struct = poscar.structure + struct = Structure.from_file(filepath) xyz = XYZ(struct) expected = """24 Fe4 P4 O16 diff --git a/tests/io/test_zeopp.py b/tests/io/test_zeopp.py index 79d1d26483a..cb2072dfe94 100644 --- a/tests/io/test_zeopp.py +++ b/tests/io/test_zeopp.py @@ -7,7 +7,6 @@ from pymatgen.analysis.bond_valence import BVAnalyzer from pymatgen.core.periodic_table import Species from pymatgen.core.structure import Molecule, Structure -from pymatgen.io.vasp.inputs import Poscar from pymatgen.io.zeopp import ( ZeoCssr, ZeoVoronoiXYZ, @@ -34,8 +33,7 @@ class TestZeoCssr(unittest.TestCase): def setUp(self): filepath = f"{TEST_FILES_DIR}/POSCAR" - p = Poscar.from_file(filepath) - self.zeocssr = ZeoCssr(p.structure) + self.zeo_cssr = ZeoCssr(Structure.from_file(filepath)) def test_str(self): expected_string = """4.7595 10.4118 6.0672 @@ -66,21 +64,20 @@ def test_str(self): 22 O 0.7146 0.8343 0.9539 0 0 0 0 0 0 0 0 0.0000 23 O 0.2587 0.9034 0.7500 0 0 0 0 0 0 0 0 0.0000 24 O 0.2929 0.9566 0.2500 0 0 0 0 0 0 0 0 0.0000""" - assert str(self.zeocssr) == expected_string + assert str(self.zeo_cssr) == expected_string def test_from_file(self): filename = f"{TEST_FILES_DIR}/EDI.cssr" - zeocssr = ZeoCssr.from_file(filename) - assert isinstance(zeocssr.structure, Structure) + zeo_cssr = ZeoCssr.from_file(filename) + assert isinstance(zeo_cssr.structure, Structure) @unittest.skipIf(not zeo, "zeo not present.") class TestZeoCssrOxi(unittest.TestCase): def setUp(self): filepath = f"{TEST_FILES_DIR}/POSCAR" - p = Poscar.from_file(filepath) - structure = BVAnalyzer().get_oxi_state_decorated_structure(p.structure) - self.zeocssr = ZeoCssr(structure) + structure = BVAnalyzer().get_oxi_state_decorated_structure(Structure.from_file(filepath)) + self.zeo_cssr = ZeoCssr(structure) def test_str(self): expected_string = """4.7595 10.4118 6.0672 @@ -111,7 +108,7 @@ def test_str(self): 22 O2- 0.7146 0.8343 0.9539 0 0 0 0 0 0 0 0 0.0000 23 O2- 0.2587 0.9034 0.7500 0 0 0 0 0 0 0 0 0.0000 24 O2- 0.2929 0.9566 0.2500 0 0 0 0 0 0 0 0 0.0000""" - assert str(self.zeocssr) == expected_string + assert str(self.zeo_cssr) == expected_string def test_from_file(self): filename = f"{TEST_FILES_DIR}/EDI_oxistate_decorated.cssr" @@ -154,8 +151,7 @@ def test_from_file(self): class TestGetVoronoiNodes(unittest.TestCase): def setUp(self): filepath = f"{TEST_FILES_DIR}/POSCAR" - p = Poscar.from_file(filepath) - self.structure = p.structure + self.structure = Structure.from_file(filepath) bv = BVAnalyzer() valences = bv.get_valences(self.structure) el = [site.species_string for site in self.structure] @@ -201,8 +197,7 @@ def test_get_free_sphere_params(self): class TestGetHighAccuracyVoronoiNodes(unittest.TestCase): def setUp(self): filepath = f"{TEST_FILES_DIR}/POSCAR" - poscar = Poscar.from_file(filepath) - self.structure = poscar.structure + self.structure = Structure.from_file(filepath) bv = BVAnalyzer() valences = bv.get_valences(self.structure) el = [site.species_string for site in self.structure] @@ -222,8 +217,7 @@ def test_get_voronoi_nodes(self): class TestGetVoronoiNodesMultiOxi(unittest.TestCase): def setUp(self): filepath = f"{TEST_FILES_DIR}/POSCAR" - p = Poscar.from_file(filepath) - self.structure = p.structure + self.structure = Structure.from_file(filepath) bv = BVAnalyzer() self.structure = bv.get_oxi_state_decorated_structure(self.structure) valences = bv.get_valences(self.structure) diff --git a/tests/io/vasp/test_inputs.py b/tests/io/vasp/test_inputs.py index da5d931bc31..0b5c9ab6097 100644 --- a/tests/io/vasp/test_inputs.py +++ b/tests/io/vasp/test_inputs.py @@ -33,11 +33,10 @@ from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest -class TestPoscar: +class TestPoscar(PymatgenTest): def test_init(self): filepath = f"{TEST_FILES_DIR}/POSCAR" - poscar = Poscar.from_file(filepath, check_for_POTCAR=False) - comp = poscar.structure.composition + comp = Structure.from_file(filepath).composition assert comp == Composition("Fe4P4O16") # VASP 4 type with symbols at the end. @@ -265,24 +264,24 @@ def test_str(self): def test_from_md_run(self): # Parsing from an MD type run with velocities and predictor corrector data - p = Poscar.from_file(f"{TEST_FILES_DIR}/CONTCAR.MD", check_for_POTCAR=False) - assert np.sum(np.array(p.velocities)) == approx(0.0065417961324) - assert p.predictor_corrector[0][0][0] == 0.33387820e00 - assert p.predictor_corrector[0][1][1] == -0.10583589e-02 + poscar = Poscar.from_file(f"{TEST_FILES_DIR}/CONTCAR.MD", check_for_POTCAR=False) + assert np.sum(np.array(poscar.velocities)) == approx(0.0065417961324) + assert poscar.predictor_corrector[0][0][0] == 0.33387820e00 + assert poscar.predictor_corrector[0][1][1] == -0.10583589e-02 def test_write_md_poscar(self): # Parsing from an MD type run with velocities and predictor corrector data # And writing a new POSCAR from the new structure - p = Poscar.from_file(f"{TEST_FILES_DIR}/CONTCAR.MD", check_for_POTCAR=False) + poscar = Poscar.from_file(f"{TEST_FILES_DIR}/CONTCAR.MD", check_for_POTCAR=False) path = Path("POSCAR.testing.md") - p.write_file(path) + poscar.write_file(path) p3 = Poscar.from_file(path) - assert_allclose(p.structure.lattice.abc, p3.structure.lattice.abc, 5) - assert_allclose(p.velocities, p3.velocities, 5) - assert_allclose(p.predictor_corrector, p3.predictor_corrector, 5) - assert p.predictor_corrector_preamble == p3.predictor_corrector_preamble + assert_allclose(poscar.structure.lattice.abc, p3.structure.lattice.abc, 5) + assert_allclose(poscar.velocities, p3.velocities, 5) + assert_allclose(poscar.predictor_corrector, p3.predictor_corrector, 5) + assert poscar.predictor_corrector_preamble == p3.predictor_corrector_preamble path.unlink() def test_setattr(self): @@ -362,11 +361,10 @@ def test_velocities(self): def test_write(self): filepath = f"{TEST_FILES_DIR}/POSCAR" poscar = Poscar.from_file(filepath) - tempfname = Path("POSCAR.testing") - poscar.write_file(tempfname) - p = Poscar.from_file(tempfname) - assert_allclose(poscar.structure.lattice.abc, p.structure.lattice.abc, 5) - tempfname.unlink() + tmp_file = f"{self.tmp_path}/POSCAR.testing" + poscar.write_file(tmp_file) + poscar = Poscar.from_file(tmp_file) + assert_allclose(poscar.structure.lattice.abc, poscar.structure.lattice.abc, 5) def test_selective_dynamics(self): filepath = f"{TEST_FILES_DIR}/POSCAR.Fe3O4" @@ -807,20 +805,19 @@ def test_static_constructors(self): assert kpoints.style == Kpoints.supported_modes.Automatic assert kpoints.kpts == [[100]] filepath = f"{TEST_FILES_DIR}/POSCAR" - poscar = Poscar.from_file(filepath) - kpoints = Kpoints.automatic_density(poscar.structure, 500) + struct = Structure.from_file(filepath) + kpoints = Kpoints.automatic_density(struct, 500) assert kpoints.kpts == [[1, 3, 3]] assert kpoints.style == Kpoints.supported_modes.Gamma - kpoints = Kpoints.automatic_density(poscar.structure, 500, force_gamma=True) + kpoints = Kpoints.automatic_density(struct, 500, force_gamma=True) assert kpoints.style == Kpoints.supported_modes.Gamma - kpoints = Kpoints.automatic_density_by_vol(poscar.structure, 1000) + kpoints = Kpoints.automatic_density_by_vol(struct, 1000) assert kpoints.kpts == [[6, 10, 13]] assert kpoints.style == Kpoints.supported_modes.Gamma - kpoints = Kpoints.automatic_density_by_lengths(poscar.structure, [50, 50, 1], force_gamma=True) + kpoints = Kpoints.automatic_density_by_lengths(struct, [50, 50, 1], force_gamma=True) assert kpoints.kpts == [[5, 9, 1]] assert kpoints.style == Kpoints.supported_modes.Gamma - struct = poscar.structure struct.make_supercell(3) kpoints = Kpoints.automatic_density(struct, 500) assert kpoints.kpts == [[1, 1, 1]] @@ -880,7 +877,7 @@ def test_automatic_kpoint(self): def test_automatic_density_by_lengths(self): # Load a structure from a POSCAR file filepath = f"{TEST_FILES_DIR}/POSCAR" - structure = Poscar.from_file(filepath).structure + structure = Structure.from_file(filepath) # test different combos of length densities and expected kpoints # TODO should test Monkhorst style case and force_gamma=True case diff --git a/tests/io/vasp/test_sets.py b/tests/io/vasp/test_sets.py index 27848e72d77..c1f7ac51380 100644 --- a/tests/io/vasp/test_sets.py +++ b/tests/io/vasp/test_sets.py @@ -132,8 +132,7 @@ class TestDictSet(PymatgenTest): @classmethod def setUpClass(cls): filepath = f"{TEST_FILES_DIR}/POSCAR" - poscar = Poscar.from_file(filepath) - cls.structure = poscar.structure + cls.structure = Structure.from_file(filepath) def test_as_dict(self): # https://github.com/materialsproject/pymatgen/pull/3031 @@ -156,8 +155,7 @@ def setUpClass(cls): cls.monkeypatch = MonkeyPatch() filepath = f"{TEST_FILES_DIR}/POSCAR" - poscar = Poscar.from_file(filepath) - cls.structure = poscar.structure + cls.structure = Structure.from_file(filepath) cls.coords = [[0, 0, 0], [0.75, 0.5, 0.75]] cls.lattice = Lattice([[3.8401979337, 0, 0], [1.9200989668, 3.3257101909, 0], [0, -2.2171384943, 3.1355090603]]) @@ -1052,8 +1050,7 @@ class TestMITMDSet(PymatgenTest): def setUp(self): self.set = MITMDSet filepath = f"{TEST_FILES_DIR}/POSCAR" - poscar = Poscar.from_file(filepath) - self.struct = poscar.structure + self.struct = Structure.from_file(filepath) self.mit_md_param = self.set(self.struct, 300, 1200, 10000) def test_params(self): @@ -1079,8 +1076,7 @@ def test_as_from_dict(self): class TestMVLNPTMDSet(PymatgenTest): def setUp(self): file_path = f"{TEST_FILES_DIR}/POSCAR" - poscar = Poscar.from_file(file_path) - self.struct = poscar.structure + self.struct = Structure.from_file(file_path) self.mvl_npt_set = MVLNPTMDSet(self.struct, start_temp=0, end_temp=300, nsteps=1000) def test_incar(self): @@ -1107,19 +1103,17 @@ def test_incar(self): assert kpoints.style == Kpoints.supported_modes.Gamma def test_as_from_dict(self): - d = self.mvl_npt_set.as_dict() - v = dec.process_decoded(d) - assert isinstance(v, MVLNPTMDSet) - assert v._config_dict["INCAR"]["NSW"] == 1000 + dct = self.mvl_npt_set.as_dict() + input_set = dec.process_decoded(dct) + assert isinstance(input_set, MVLNPTMDSet) + assert input_set._config_dict["INCAR"]["NSW"] == 1000 class TestMPMDSet(PymatgenTest): def setUp(self): filepath = f"{TEST_FILES_DIR}/POSCAR" - poscar = Poscar.from_file(filepath) - poscar_with_h = Poscar.from_file(f"{TEST_FILES_DIR}/POSCAR_hcp", check_for_POTCAR=False) - self.struct = poscar.structure - self.struct_with_H = poscar_with_h.structure + self.struct = Structure.from_file(filepath) + self.struct_with_H = Structure.from_file(f"{TEST_FILES_DIR}/POSCAR_hcp") self.mp_md_set_noTS = MPMDSet(self.struct, start_temp=0, end_temp=300, nsteps=1000) self.mp_md_set_noTS_with_H = MPMDSet(self.struct_with_H, start_temp=0, end_temp=300, nsteps=1000) self.mp_md_set_TS1 = MPMDSet(self.struct, start_temp=0, end_temp=300, nsteps=1000, time_step=1.0) @@ -1455,8 +1449,7 @@ class TestMVLScanRelaxSet(PymatgenTest): def setUp(self): self.set = MVLScanRelaxSet file_path = f"{TEST_FILES_DIR}/POSCAR" - poscar = Poscar.from_file(file_path) - self.struct = poscar.structure + self.struct = Structure.from_file(file_path) self.mvl_scan_set = self.set(self.struct, user_potcar_functional="PBE_52", user_incar_settings={"NSW": 500}) def test_incar(self): @@ -1507,8 +1500,7 @@ def test_as_from_dict(self): class TestMPScanRelaxSet(PymatgenTest): def setUp(self): file_path = f"{TEST_FILES_DIR}/POSCAR" - poscar = Poscar.from_file(file_path) - self.struct = poscar.structure + self.struct = Structure.from_file(file_path) self.mp_scan_set = MPScanRelaxSet( self.struct, user_potcar_functional="PBE_52", user_incar_settings={"NSW": 500} ) @@ -1555,7 +1547,7 @@ def test_bandgap_tol(self): def test_kspacing(self): # Test that KSPACING is capped at 0.44 for insulators file_path = f"{TEST_FILES_DIR}/POSCAR.O2" - struct = Poscar.from_file(file_path, check_for_POTCAR=False).structure + struct = Structure.from_file(file_path) for bandgap, expected in ((10, 0.44), (3, 0.4136617), (1.1, 0.3064757), (0.5, 0.2832948), (0, 0.22)): incar = MPScanRelaxSet(struct, bandgap=bandgap).incar assert incar["KSPACING"] == approx(expected, abs=1e-5) @@ -1748,8 +1740,7 @@ class TestMVLRelax52Set(PymatgenTest): def setUp(self): self.set = MVLRelax52Set file_path = f"{TEST_FILES_DIR}/POSCAR" - poscar = Poscar.from_file(file_path) - self.struct = poscar.structure + self.struct = Structure.from_file(file_path) self.mvl_rlx_set = self.set(self.struct, user_potcar_functional="PBE_54", user_incar_settings={"NSW": 500}) def test_incar(self): @@ -1782,8 +1773,7 @@ class TestLobsterSet(PymatgenTest): def setUp(self): self.set = LobsterSet file_path = f"{TEST_FILES_DIR}/POSCAR" - poscar = Poscar.from_file(file_path) - self.struct = poscar.structure + self.struct = Structure.from_file(file_path) # test for different parameters! self.lobsterset1 = self.set(self.struct, isym=-1, ismear=-5) self.lobsterset2 = self.set(self.struct, isym=0, ismear=0) @@ -1863,8 +1853,7 @@ def test_as_from_dict(self): class TestMPAbsorptionSet(PymatgenTest): def setUp(self): file_path = f"{TEST_FILES_DIR}/absorption/static/POSCAR" - poscar = Poscar.from_file(file_path) - self.structure = poscar.structure + self.structure = Structure.from_file(file_path) def test_ipa(self): prev_run = f"{TEST_FILES_DIR}/absorption/static" diff --git a/tests/symmetry/test_analyzer.py b/tests/symmetry/test_analyzer.py index 6ca2189ed8c..2e07003c155 100644 --- a/tests/symmetry/test_analyzer.py +++ b/tests/symmetry/test_analyzer.py @@ -10,7 +10,6 @@ from pymatgen.core.periodic_table import Species from pymatgen.core.sites import PeriodicSite from pymatgen.core.structure import Molecule, Structure -from pymatgen.io.vasp.inputs import Poscar from pymatgen.io.vasp.outputs import Vasprun from pymatgen.symmetry.analyzer import PointGroupAnalyzer, SpacegroupAnalyzer, cluster_sites, iterative_symmetrize from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest @@ -20,12 +19,11 @@ class TestSpacegroupAnalyzer(PymatgenTest): def setUp(self): - p = Poscar.from_file(f"{TEST_FILES_DIR}/POSCAR") - self.structure = p.structure + self.structure = Structure.from_file(f"{TEST_FILES_DIR}/POSCAR") self.sg = SpacegroupAnalyzer(self.structure, 0.001) self.disordered_structure = self.get_structure("Li10GeP2S12") self.disordered_sg = SpacegroupAnalyzer(self.disordered_structure, 0.001) - struct = p.structure.copy() + struct = self.structure.copy() site = struct[0] del struct[0] struct.append(site.species, site.frac_coords) @@ -382,8 +380,7 @@ def test_tricky_structure(self): class TestSpacegroup(unittest.TestCase): def setUp(self): - p = Poscar.from_file(f"{TEST_FILES_DIR}/POSCAR") - self.structure = p.structure + self.structure = Structure.from_file(f"{TEST_FILES_DIR}/POSCAR") self.sg1 = SpacegroupAnalyzer(self.structure, 0.001).get_space_group_operations() def test_are_symmetrically_equivalent(self): diff --git a/tests/transformations/test_advanced_transformations.py b/tests/transformations/test_advanced_transformations.py index e769c46f6fe..df437e1c348 100644 --- a/tests/transformations/test_advanced_transformations.py +++ b/tests/transformations/test_advanced_transformations.py @@ -17,7 +17,6 @@ from pymatgen.core.structure import Molecule, Structure from pymatgen.core.surface import SlabGenerator from pymatgen.io.cif import CifParser -from pymatgen.io.vasp.inputs import Poscar from pymatgen.symmetry.analyzer import SpacegroupAnalyzer from pymatgen.transformations.advanced_transformations import ( AddAdsorbateTransformation, @@ -172,8 +171,7 @@ class TestEnumerateStructureTransformation(unittest.TestCase): def test_apply_transformation(self): enum_trans = EnumerateStructureTransformation(refine_structure=True) enum_trans2 = EnumerateStructureTransformation(refine_structure=True, sort_criteria="nsites") - p = Poscar.from_file(f"{TEST_FILES_DIR}/POSCAR.LiFePO4", check_for_POTCAR=False) - struct = p.structure + struct = Structure.from_file(f"{TEST_FILES_DIR}/POSCAR.LiFePO4") expected = [1, 3, 1] for idx, frac in enumerate([0.25, 0.5, 0.75]): trans = SubstitutionTransformation({"Fe": {"Fe": frac}}) @@ -203,8 +201,7 @@ def test_apply_transformation(self): def test_m3gnet(self): pytest.importorskip("matgl") enum_trans = EnumerateStructureTransformation(refine_structure=True, sort_criteria="m3gnet_relax") - p = Poscar.from_file(f"{TEST_FILES_DIR}/POSCAR.LiFePO4", check_for_POTCAR=False) - struct = p.structure + struct = Structure.from_file(f"{TEST_FILES_DIR}/POSCAR.LiFePO4") trans = SubstitutionTransformation({"Fe": {"Fe": 0.5, "Mn": 0.5}}) s = trans.apply_transformation(struct) alls = enum_trans.apply_transformation(s, 100) @@ -230,8 +227,7 @@ def sort_criteria(s): return relax_results["final_structure"], energy enum_trans = EnumerateStructureTransformation(refine_structure=True, sort_criteria=sort_criteria) - p = Poscar.from_file(f"{TEST_FILES_DIR}/POSCAR.LiFePO4", check_for_POTCAR=False) - struct = p.structure + struct = Structure.from_file(f"{TEST_FILES_DIR}/POSCAR.LiFePO4") trans = SubstitutionTransformation({"Fe": {"Fe": 0.5, "Mn": 0.5}}) s = trans.apply_transformation(struct) alls = enum_trans.apply_transformation(s, 100) @@ -317,8 +313,7 @@ def setUp(self): def test_apply_transformation(self): trans = MagOrderingTransformation({"Fe": 5}) - p = Poscar.from_file(f"{TEST_FILES_DIR}/POSCAR.LiFePO4", check_for_POTCAR=False) - struct = p.structure + struct = Structure.from_file(f"{TEST_FILES_DIR}/POSCAR.LiFePO4") alls = trans.apply_transformation(struct, 10) assert len(alls) == 3 f = SpacegroupAnalyzer(alls[0]["structure"], 0.1) @@ -348,8 +343,7 @@ def test_apply_transformation(self): def test_ferrimagnetic(self): trans = MagOrderingTransformation({"Fe": 5}, order_parameter=0.75, max_cell_size=1) - p = Poscar.from_file(f"{TEST_FILES_DIR}/POSCAR.LiFePO4", check_for_POTCAR=False) - struct = p.structure + struct = Structure.from_file(f"{TEST_FILES_DIR}/POSCAR.LiFePO4") a = SpacegroupAnalyzer(struct, 0.1) struct = a.get_refined_structure() alls = trans.apply_transformation(struct, 10) diff --git a/tests/transformations/test_standard_transformations.py b/tests/transformations/test_standard_transformations.py index c590e3bbd98..66372b7497c 100644 --- a/tests/transformations/test_standard_transformations.py +++ b/tests/transformations/test_standard_transformations.py @@ -14,7 +14,6 @@ from pymatgen.core.lattice import Lattice from pymatgen.core.periodic_table import Element from pymatgen.core.sites import PeriodicSite -from pymatgen.io.vasp.inputs import Poscar from pymatgen.symmetry.structure import SymmetrizedStructure from pymatgen.transformations.standard_transformations import ( AutoOxiStateDecorationTransformation, @@ -199,9 +198,8 @@ def test_apply_transformation(self): class TestAutoOxiStateDecorationTransformation(unittest.TestCase): def test_apply_transformation(self): - p = Poscar.from_file(f"{TEST_FILES_DIR}/POSCAR.LiFePO4", check_for_POTCAR=False) trafo = AutoOxiStateDecorationTransformation() - struct = trafo.apply_transformation(p.structure) + struct = trafo.apply_transformation(Structure.from_file(f"{TEST_FILES_DIR}/POSCAR.LiFePO4")) expected_oxi = {"Li": 1, "P": 5, "O": -2, "Fe": 2} for site in struct: assert site.specie.oxi_state == expected_oxi[site.specie.symbol] @@ -263,16 +261,14 @@ def test_apply_transformation_fast(self): assert fast_opt_s == slow_opt_s def test_apply_transformations_complete_ranking(self): - p = Poscar.from_file(f"{TEST_FILES_DIR}/POSCAR.LiFePO4", check_for_POTCAR=False) t1 = OxidationStateDecorationTransformation({"Li": 1, "Fe": 2, "P": 5, "O": -2}) - struct = t1.apply_transformation(p.structure) + struct = t1.apply_transformation(Structure.from_file(f"{TEST_FILES_DIR}/POSCAR.LiFePO4")) trafo = PartialRemoveSpecieTransformation("Li+", 0.5, PartialRemoveSpecieTransformation.ALGO_COMPLETE) assert len(trafo.apply_transformation(struct, 10)) == 6 def test_apply_transformations_best_first(self): - p = Poscar.from_file(f"{TEST_FILES_DIR}/POSCAR.LiFePO4", check_for_POTCAR=False) t1 = OxidationStateDecorationTransformation({"Li": 1, "Fe": 2, "P": 5, "O": -2}) - struct = t1.apply_transformation(p.structure) + struct = t1.apply_transformation(Structure.from_file(f"{TEST_FILES_DIR}/POSCAR.LiFePO4")) trafo = PartialRemoveSpecieTransformation("Li+", 0.5, PartialRemoveSpecieTransformation.ALGO_BEST_FIRST) assert len(trafo.apply_transformation(struct)) == 26