Skip to content

Commit

Permalink
simplify Poscar.from_file().structure to Structure.from_file()
Browse files Browse the repository at this point in the history
  • Loading branch information
janosh committed Oct 14, 2023
1 parent 6340c4b commit 6c508c0
Show file tree
Hide file tree
Showing 18 changed files with 102 additions and 164 deletions.
10 changes: 3 additions & 7 deletions pymatgen/analysis/surface_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,25 +38,22 @@
import itertools
import random
import warnings
from typing import TYPE_CHECKING

import matplotlib.pyplot as plt
import numpy as np
from sympy import Symbol
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"
Expand Down Expand Up @@ -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,
Expand Down
7 changes: 4 additions & 3 deletions pymatgen/analysis/transition_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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):
Expand Down
10 changes: 4 additions & 6 deletions tests/analysis/test_ewald.py
Original file line number Diff line number Diff line change
Expand Up @@ -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})

Expand Down Expand Up @@ -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
Expand Down
13 changes: 5 additions & 8 deletions tests/analysis/test_structure_analyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down
7 changes: 2 additions & 5 deletions tests/command_line/test_gulp_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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)

Expand Down
4 changes: 1 addition & 3 deletions tests/core/test_trajectory.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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):
Expand Down
13 changes: 1 addition & 12 deletions tests/io/test_ase.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -30,28 +28,24 @@ 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)
assert atoms.get_array("prop").tolist() == prop


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)
Expand All @@ -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)
Expand All @@ -86,15 +77,13 @@ 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)
assert atoms.get_array("oxi_states").tolist() == 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]
Expand Down
16 changes: 7 additions & 9 deletions tests/io/test_cif.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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
Expand Down
4 changes: 1 addition & 3 deletions tests/io/test_cssr.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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
Expand Down
21 changes: 11 additions & 10 deletions tests/io/test_jarvis.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
5 changes: 2 additions & 3 deletions tests/io/test_xr.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down
5 changes: 2 additions & 3 deletions tests/io/test_xyz.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
Loading

0 comments on commit 6c508c0

Please sign in to comment.