Exemplo n.º 1
0
    def test_get_xrd_data(self):
        a = 4.209
        latt = Lattice.cubic(a)
        structure = Structure(latt, ["Cs", "Cl"], [[0, 0, 0], [0.5, 0.5, 0.5]])
        c = XRDCalculator()
        data = c.get_xrd_data(structure, two_theta_range=(0, 90))
        #Check the first two peaks
        self.assertAlmostEqual(data[0][0], 21.107738329639844)
        self.assertAlmostEqual(data[0][1], 36.483184003748946)
        self.assertEqual(data[0][2], {(1, 0, 0): 6})
        self.assertAlmostEqual(data[0][3], 4.2089999999999996)
        self.assertAlmostEqual(data[1][0], 30.024695921112777)
        self.assertAlmostEqual(data[1][1], 100)
        self.assertEqual(data[1][2], {(1, 1, 0): 12})
        self.assertAlmostEqual(data[1][3], 2.976212442014178)

        s = read_structure(os.path.join(test_dir, "LiFePO4.cif"))
        data = c.get_xrd_data(s, two_theta_range=(0, 90))
        self.assertAlmostEqual(data[1][0], 17.03504233621785)
        self.assertAlmostEqual(data[1][1], 50.400928948337075)

        s = read_structure(os.path.join(test_dir, "Li10GeP2S12.cif"))
        data = c.get_xrd_data(s, two_theta_range=(0, 90))
        self.assertAlmostEqual(data[1][0], 14.058274883353876)
        self.assertAlmostEqual(data[1][1], 4.4111123641667671)

        # Test a hexagonal structure.
        s = read_structure(os.path.join(test_dir, "Graphite.cif"),
                           primitive=False)
        data = c.get_xrd_data(s, two_theta_range=(0, 90))
        self.assertAlmostEqual(data[0][0], 7.929279053132362)
        self.assertAlmostEqual(data[0][1], 100)
        self.assertAlmostEqual(len(list(data[0][2].keys())[0]), 4)

        #Add test case with different lengths of coefficients.
        #Also test d_hkl.
        coords = [[0.25, 0.25, 0.173], [0.75, 0.75, 0.827], [0.75, 0.25, 0],
                  [0.25, 0.75, 0], [0.25, 0.25, 0.676], [0.75, 0.75, 0.324]]
        sp = ["Si", "Si", "Ru", "Ru", "Pr", "Pr"]
        s = Structure(Lattice.tetragonal(4.192, 6.88), sp, coords)
        data = c.get_xrd_data(s)
        self.assertAlmostEqual(data[0][0], 12.86727341476735)
        self.assertAlmostEqual(data[0][1], 31.448239816769796)
        self.assertAlmostEqual(data[0][3], 6.88)
        self.assertEqual(len(data), 42)
        data = c.get_xrd_data(s, two_theta_range=[0, 60])
        self.assertEqual(len(data), 18)

        #Test with and without Debye-Waller factor
        tungsten = Structure(Lattice.cubic(3.1653), ["W"] * 2,
                             [[0, 0, 0], [0.5, 0.5, 0.5]])
        data = c.get_xrd_data(tungsten, scaled=False)
        self.assertAlmostEqual(data[0][0], 40.294828554672264)
        self.assertAlmostEqual(data[0][1], 2414237.5633093244)
        self.assertAlmostEqual(data[0][3], 2.2382050944897789)
        c = XRDCalculator(debye_waller_factors={"W": 0.1526})
        data = c.get_xrd_data(tungsten, scaled=False)
        self.assertAlmostEqual(data[0][0], 40.294828554672264)
        self.assertAlmostEqual(data[0][1], 2377745.2296686019)
        self.assertAlmostEqual(data[0][3], 2.2382050944897789)
Exemplo n.º 2
0
    def test_fit(self):
        """
        Take two known matched structures
            1) Ensure match
            2) Ensure match after translation and rotations
            3) Ensure no-match after large site translation
            4) Ensure match after site shuffling
            """
        sm = StructureMatcher()

        self.assertTrue(sm.fit(self.struct_list[0], self.struct_list[1]))

        # Test rotational/translational invariance
        op = SymmOp.from_axis_angle_and_translation([0, 0, 1], 30, False,
                                                    np.array([0.4, 0.7, 0.9]))
        self.struct_list[1].apply_operation(op)
        self.assertTrue(sm.fit(self.struct_list[0], self.struct_list[1]))

        #Test failure under large atomic translation
        self.struct_list[1].translate_sites([0], [.4, .4, .2],
                                            frac_coords=True)
        self.assertFalse(sm.fit(self.struct_list[0], self.struct_list[1]))

        self.struct_list[1].translate_sites([0], [-.4, -.4, -.2],
                                            frac_coords=True)
        # random.shuffle(editor._sites)
        self.assertTrue(sm.fit(self.struct_list[0], self.struct_list[1]))
        #Test FrameworkComporator
        sm2 = StructureMatcher(comparator=FrameworkComparator())
        lfp = read_structure(os.path.join(test_dir, "LiFePO4.cif"))
        nfp = read_structure(os.path.join(test_dir, "NaFePO4.cif"))
        self.assertTrue(sm2.fit(lfp, nfp))
        self.assertFalse(sm.fit(lfp, nfp))

        #Test anonymous fit.
        self.assertEqual(sm.fit_anonymous(lfp, nfp),
                         {Composition("Li"): Composition("Na")})
        self.assertAlmostEqual(sm.get_minimax_rms_anonymous(lfp, nfp)[0],
                               0.096084154118549828)

        #Test partial occupancies.
        s1 = Structure([[3, 0, 0], [0, 3, 0], [0, 0, 3]],
                       [{"Fe": 0.5}, {"Fe": 0.5}, {"Fe": 0.5}, {"Fe": 0.5}],
                       [[0, 0, 0], [0.25, 0.25, 0.25],
                        [0.5, 0.5, 0.5], [0.75, 0.75, 0.75]])
        s2 = Structure([[3, 0, 0], [0, 3, 0], [0, 0, 3]],
                       [{"Fe": 0.25}, {"Fe": 0.5}, {"Fe": 0.5}, {"Fe": 0.75}],
                       [[0, 0, 0], [0.25, 0.25, 0.25],
                        [0.5, 0.5, 0.5], [0.75, 0.75, 0.75]])
        self.assertFalse(sm.fit(s1, s2))
        self.assertFalse(sm.fit(s2, s1))
        s2 = Structure([[3, 0, 0], [0, 3, 0], [0, 0, 3]],
                       [{"Fe": 0.25}, {"Fe": 0.25}, {"Fe": 0.25},
                        {"Fe": 0.25}],
                       [[0, 0, 0], [0.25, 0.25, 0.25],
                        [0.5, 0.5, 0.5], [0.75, 0.75, 0.75]])
        self.assertEqual(sm.fit_anonymous(s1, s2),
                         {Composition("Fe0.5"): Composition("Fe0.25")})

        self.assertAlmostEqual(sm.get_minimax_rms_anonymous(s1, s2)[0], 0)
Exemplo n.º 3
0
    def test_electronegativity(self):
        sm = StructureMatcher(ltol=0.2, stol=0.3, angle_tol=5)

        s1 = read_structure(os.path.join(test_dir, "Na2Fe2PAsO4S4.cif"))
        s2 = read_structure(os.path.join(test_dir, "Na2Fe2PNO4Se4.cif"))
        self.assertAlmostEqual(sm.fit_with_electronegativity(s1, s2),
                               {Composition('S'): Composition('Se'), Composition('As'): Composition('N')})
Exemplo n.º 4
0
    def test_fit(self):
        """
        Take two known matched structures
            1) Ensure match
            2) Ensure match after translation and rotations
            3) Ensure no-match after large site translation
            4) Ensure match after site shuffling
            """
        sm = StructureMatcher()

        self.assertTrue(sm.fit(self.struct_list[0], self.struct_list[1]))

        # Test rotational/translational invariance
        op = SymmOp.from_axis_angle_and_translation([0, 0, 1], 30, False,
                                                    np.array([0.4, 0.7, 0.9]))
        self.struct_list[1].apply_operation(op)
        self.assertTrue(sm.fit(self.struct_list[0], self.struct_list[1]))

        #Test failure under large atomic translation
        self.struct_list[1].translate_sites([0], [.4, .4, .2],
                                            frac_coords=True)
        self.assertFalse(sm.fit(self.struct_list[0], self.struct_list[1]))

        self.struct_list[1].translate_sites([0], [-.4, -.4, -.2],
                                            frac_coords=True)
        # random.shuffle(editor._sites)
        self.assertTrue(sm.fit(self.struct_list[0], self.struct_list[1]))
        #Test FrameworkComporator
        sm2 = StructureMatcher(comparator=FrameworkComparator())
        lfp = read_structure(os.path.join(test_dir, "LiFePO4.cif"))
        nfp = read_structure(os.path.join(test_dir, "NaFePO4.cif"))
        self.assertTrue(sm2.fit(lfp, nfp))
        self.assertFalse(sm.fit(lfp, nfp))

        #Test anonymous fit.
        self.assertEqual(sm.fit_anonymous(lfp, nfp),
                         {Composition("Li"): Composition("Na")})
        self.assertAlmostEqual(sm.get_minimax_rms_anonymous(lfp, nfp)[0],
                               0.096084154118549828)

        #Test partial occupancies.
        s1 = Structure([[3, 0, 0], [0, 3, 0], [0, 0, 3]],
                       [{"Fe": 0.5}, {"Fe": 0.5}, {"Fe": 0.5}, {"Fe": 0.5}],
                       [[0, 0, 0], [0.25, 0.25, 0.25],
                        [0.5, 0.5, 0.5], [0.75, 0.75, 0.75]])
        s2 = Structure([[3, 0, 0], [0, 3, 0], [0, 0, 3]],
                       [{"Fe": 0.25}, {"Fe": 0.5}, {"Fe": 0.5}, {"Fe": 0.75}],
                       [[0, 0, 0], [0.25, 0.25, 0.25],
                        [0.5, 0.5, 0.5], [0.75, 0.75, 0.75]])
        self.assertFalse(sm.fit(s1, s2))
        self.assertFalse(sm.fit(s2, s1))
        s2 = Structure([[3, 0, 0], [0, 3, 0], [0, 0, 3]],
                       [{"Fe": 0.25}, {"Fe": 0.25}, {"Fe": 0.25},
                        {"Fe": 0.25}],
                       [[0, 0, 0], [0.25, 0.25, 0.25],
                        [0.5, 0.5, 0.5], [0.75, 0.75, 0.75]])
        self.assertEqual(sm.fit_anonymous(s1, s2),
                         {Composition("Fe0.5"): Composition("Fe0.25")})

        self.assertAlmostEqual(sm.get_minimax_rms_anonymous(s1, s2)[0], 0)
Exemplo n.º 5
0
    def test_get_xrd_data(self):
        a = 4.209
        latt = Lattice.cubic(a)
        structure = Structure(latt, ["Cs", "Cl"], [[0, 0, 0], [0.5, 0.5, 0.5]])
        c = XRDCalculator()
        data = c.get_xrd_data(structure, two_theta_range=(0, 90))
        #Check the first two peaks
        self.assertAlmostEqual(data[0][0], 21.107738329639844)
        self.assertAlmostEqual(data[0][1], 36.483184003748946)
        self.assertEqual(data[0][2], {(1, 0, 0): 6})
        self.assertAlmostEqual(data[0][3], 4.2089999999999996)
        self.assertAlmostEqual(data[1][0], 30.024695921112777)
        self.assertAlmostEqual(data[1][1], 100)
        self.assertEqual(data[1][2], {(1, 1, 0): 12})
        self.assertAlmostEqual(data[1][3], 2.976212442014178)

        s = read_structure(os.path.join(test_dir, "LiFePO4.cif"))
        data = c.get_xrd_data(s, two_theta_range=(0, 90))
        self.assertAlmostEqual(data[1][0], 17.03504233621785)
        self.assertAlmostEqual(data[1][1], 50.400928948337075)

        s = read_structure(os.path.join(test_dir, "Li10GeP2S12.cif"))
        data = c.get_xrd_data(s, two_theta_range=(0, 90))
        self.assertAlmostEqual(data[1][0], 14.058274883353876)
        self.assertAlmostEqual(data[1][1], 4.4111123641667671)

        # Test a hexagonal structure.
        s = read_structure(os.path.join(test_dir, "Graphite.cif"),
                           primitive=False)
        data = c.get_xrd_data(s, two_theta_range=(0, 90))
        self.assertAlmostEqual(data[0][0], 7.929279053132362)
        self.assertAlmostEqual(data[0][1], 100)
        self.assertAlmostEqual(len(list(data[0][2].keys())[0]), 4)

        #Add test case with different lengths of coefficients.
        #Also test d_hkl.
        coords = [[0.25, 0.25, 0.173], [0.75, 0.75, 0.827], [0.75, 0.25, 0],
                  [0.25, 0.75, 0], [0.25, 0.25, 0.676], [0.75, 0.75, 0.324]]
        sp = ["Si", "Si", "Ru", "Ru", "Pr", "Pr"]
        s = Structure(Lattice.tetragonal(4.192, 6.88), sp, coords)
        data = c.get_xrd_data(s)
        self.assertAlmostEqual(data[0][0], 12.86727341476735)
        self.assertAlmostEqual(data[0][1], 31.448239816769796)
        self.assertAlmostEqual(data[0][3], 6.88)
        self.assertEqual(len(data), 42)
        data = c.get_xrd_data(s, two_theta_range=[0, 60])
        self.assertEqual(len(data), 18)

        #Test with and without Debye-Waller factor
        tungsten = Structure(Lattice.cubic(3.1653), ["W"] * 2,
                             [[0, 0, 0], [0.5, 0.5, 0.5]])
        data = c.get_xrd_data(tungsten, scaled=False)
        self.assertAlmostEqual(data[0][0], 40.294828554672264)
        self.assertAlmostEqual(data[0][1], 2414237.5633093244)
        self.assertAlmostEqual(data[0][3], 2.2382050944897789)
        c = XRDCalculator(debye_waller_factors={"W": 0.1526})
        data = c.get_xrd_data(tungsten, scaled=False)
        self.assertAlmostEqual(data[0][0], 40.294828554672264)
        self.assertAlmostEqual(data[0][1], 2377745.2296686019)
        self.assertAlmostEqual(data[0][3], 2.2382050944897789)
    def test_supercell_fit(self):
        sm = StructureMatcher(attempt_supercell=False)
        s1 = read_structure(os.path.join(test_dir, "Al3F9.cif"))
        s2 = read_structure(os.path.join(test_dir, "Al3F9_distorted.cif"))

        self.assertFalse(sm.fit(s1, s2))

        sm = StructureMatcher(attempt_supercell=True)

        self.assertTrue(sm.fit(s1, s2))
Exemplo n.º 7
0
    def test_supercell_fit(self):
        sm = StructureMatcher(attempt_supercell=False)
        s1 = read_structure(os.path.join(test_dir, "Al3F9.cif"))
        s2 = read_structure(os.path.join(test_dir, "Al3F9_distorted.cif"))

        self.assertFalse(sm.fit(s1, s2))

        sm = StructureMatcher(attempt_supercell=True)

        self.assertTrue(sm.fit(s1, s2))
Exemplo n.º 8
0
 def test_read_structure(self):
     test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..",
                             'test_files')
     for fname in ("Li2O.cif", "Li2O2.cif", "vasprun.xml",
                   "vasprun_Si_bands.xml", "Si.cssr"):
         filename = os.path.join(test_dir, fname)
         struct = read_structure(filename)
         self.assertIsInstance(struct, Structure)
         prim = read_structure(filename, primitive=True)
         self.assertLessEqual(len(prim), len(struct))
         sorted_s = read_structure(filename, sort=True)
         self.assertEqual(sorted_s, sorted_s.get_sorted_structure())
Exemplo n.º 9
0
 def test_read_structure(self):
     test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..",
                             'test_files')
     for fname in ("Li2O.cif", "Li2O2.cif", "vasprun.xml",
                   "vasprun_Si_bands.xml", "Si.cssr"):
         filename = os.path.join(test_dir, fname)
         struct = read_structure(filename)
         self.assertIsInstance(struct, Structure)
         prim = read_structure(filename, primitive=True)
         self.assertLessEqual(len(prim), len(struct))
         sorted_s = read_structure(filename, sort=True)
         self.assertEqual(sorted_s, sorted_s.get_sorted_structure())
Exemplo n.º 10
0
def scaleCell(path,volume):
    poscar = os.path.join(path,'POSCAR')
    refcar = os.path.join(path,'REFCAR')
    potcar = Potcar()

    assert os.path.isfile(poscar)

    struct = read_structure(poscar)
    struct.scale_lattice(volume)
    species = [ pot.element for pot in potcar.from_file('POTCAR') ]
    reprule = { old:new  for old,new in zip(struct.composition.elements,species) }
    struct.replace_species(reprule)

    p = Poscar(struct)

    with open(poscar) as f:
        poscomment = f.readline().strip()

    p.comment = poscomment
    p.write_file(poscar,vasp4_compatible=True)

    if os.path.isfile(refcar):
        tmp = os.path.join(path,'POSCARtmp')

        # copy Poscar to temporary file and refcar to poscar
        copyfile(poscar,tmp)
        copyfile(refcar,poscar)

        struct = read_structure(poscar)
        struct.scale_lattice(volume)
        species = [ pot.element for pot in potcar.from_file('POTCAR') ]
        reprule = { old:new  for old,new in zip(struct.composition.elements,species) }
        struct.replace_species(reprule)

        r = Poscar(struct)

        with open(poscar) as f:
            poscomment = f.readline().strip()

        r.comment = poscomment
        r.write_file(poscar,vasp4_compatible=True)

        with open(refcar) as f:
            poscomment = f.readline().strip()

        r.comment = poscomment
        r.write_file(refcar,vasp4_compatible=True)

        # replace poscar with its original
        move(tmp,poscar)
    else:
        print 'No REFCAR found.'
Exemplo n.º 11
0
    def test_electronegativity(self):
        sm = StructureMatcher(ltol=0.2, stol=0.3, angle_tol=5)

        s1 = read_structure(os.path.join(test_dir, "Na2Fe2PAsO4S4.cif"))
        s2 = read_structure(os.path.join(test_dir, "Na2Fe2PNO4Se4.cif"))
        self.assertEqual(sm.get_best_electronegativity_anonymous_mapping(s1, s2),
                    {Element('S'): Element('Se'),
                     Element('As'): Element('N'),
                     Element('Fe'): Element('Fe'),
                     Element('Na'): Element('Na'),
                     Element('P'): Element('P'),
                     Element('O'): Element('O'),})
        self.assertEqual(len(sm.get_all_anonymous_mappings(s1, s2)), 2)
Exemplo n.º 12
0
    def test_electronegativity(self):
        sm = StructureMatcher(ltol=0.2, stol=0.3, angle_tol=5)

        s1 = read_structure(os.path.join(test_dir, "Na2Fe2PAsO4S4.cif"))
        s2 = read_structure(os.path.join(test_dir, "Na2Fe2PNO4Se4.cif"))
        self.assertEqual(
            sm.get_best_electronegativity_anonymous_mapping(s1, s2), {
                Element('S'): Element('Se'),
                Element('As'): Element('N'),
                Element('Fe'): Element('Fe'),
                Element('Na'): Element('Na'),
                Element('P'): Element('P'),
                Element('O'): Element('O'),
            })
        self.assertEqual(len(sm.get_all_anonymous_mappings(s1, s2)), 2)
Exemplo n.º 13
0
def asabistructure(obj):
    """
    Convert obj into an AbiStructure object. Accepts:

        - AbiStructure instance
        - Subinstances of pymatgen.
        - File paths
    """
    if isinstance(obj, AbiStructure):
        return obj

    if isinstance(obj, Structure):
        # Promote
        return AbiStructure(obj)

    if is_string(obj):
        # Handle file paths.
        if os.path.isfile(obj):

            if obj.endswith(".nc"):
                structure = structure_from_etsf_file(obj)
                #print(structure._sites)
            else:
                structure = read_structure(obj)

            # Promote
            return AbiStructure(structure)

    raise ValueError("Don't know how to convert object %s to an AbiStructure structure" % str(obj))
Exemplo n.º 14
0
    def from_file(cls, filepath):
        """
        Return a new Structure instance from a NetCDF file 

        Args:
            filename:
                netcdf file with crystallographic data in the ETSF-IO format.
                or any other file format supported by `pymatgen.io.smartio`.
        """
        if filepath.endswith(".nc"):
            file, closeit = as_etsfreader(filepath)

            new = file.read_structure()
            # Change the class of new.
            new.__class__ = cls

            new.set_spacegroup(SpaceGroup.from_file(file))

            if closeit:
                file.close()
        else:
            # TODO: Spacegroup is missing here.
            from pymatgen.io.smartio import read_structure
            new = read_structure(filepath)
            # Change the class of new.
            new.__class__ = cls

        return new
Exemplo n.º 15
0
 def test_read_structure(self):
     for fname in ("Li2O.cif", "Li2O2.cif", "vasprun.xml",
                   "vasprun_Si_bands.xml", "Si.cssr"):
         filename = os.path.join(test_dir, fname)
         struct = read_structure(filename)
         self.assertIsInstance(struct, Structure)
         print struct
Exemplo n.º 16
0
def asabistructure(obj):
    """
    Convert obj into an AbiStructure object. Accepts:

        - AbiStructure instance
        - Subinstances of pymatgen.
        - File paths
    """
    if isinstance(obj, AbiStructure):
        return obj

    if isinstance(obj, Structure):
        # Promote
        return AbiStructure(obj)

    if isinstance(obj, str):
        # Handle file paths.
        if os.path.isfile(obj):

            if obj.endswith(".nc"):
                from .netcdf import structure_from_etsf_file
                structure = structure_from_etsf_file(obj)
                print(structure._sites)
            else:
                from pymatgen.io.smartio import read_structure
                structure = read_structure(obj)

            # Promote
            return AbiStructure(structure)

    raise ValueError("Don't know how to convert object %s to an AbiStructure structure" % str(obj))
    def test_apply_transformation(self):
        trans = MagOrderingTransformation({"Fe": 5})
        p = Poscar.from_file(os.path.join(test_dir, 'POSCAR.LiFePO4'),
                             check_for_POTCAR=False)
        s = p.structure
        alls = trans.apply_transformation(s, 10)
        self.assertEqual(len(alls), 3)
        f = SymmetryFinder(alls[0]["structure"], 0.1)
        self.assertEqual(f.get_spacegroup_number(), 31)

        model = IsingModel(5, 5)
        trans = MagOrderingTransformation({"Fe": 5},
                                          energy_model=model)
        alls2 = trans.apply_transformation(s, 10)
        #Ising model with +J penalizes similar neighbor magmom.
        self.assertNotEqual(alls[0]["structure"], alls2[0]["structure"])
        self.assertEqual(alls[0]["structure"], alls2[2]["structure"])

        from pymatgen.io.smartio import read_structure
        s = read_structure(os.path.join(test_dir, 'Li2O.cif'))
        #Li2O doesn't have magnetism of course, but this is to test the
        # enumeration.
        trans = MagOrderingTransformation({"Li+": 1}, max_cell_size=3)
        alls = trans.apply_transformation(s, 100)
        self.assertEqual(len(alls), 10)
Exemplo n.º 18
0
def generate_diffraction_plot(args):
    s = read_structure(args.filenames[0])
    c = XRDCalculator()
    if args.outfile:
        c.get_xrd_plot(s).savefig(args.outfile[0])
    else:
        c.show_xrd_plot(s)
Exemplo n.º 19
0
    def __init__(self,
                 workdir,
                 runmode,
                 structure_or_cif,
                 pseudos,
                 kppa,
                 spin_mode="polarized",
                 smearing="fermi_dirac:0.1 eV",
                 accuracy="normal",
                 ecut=None,
                 ecutsm=0.05,
                 chksymbreak=0):  # FIXME Hack

        super(DeltaTest, self).__init__(workdir, runmode)

        if isinstance(structure_or_cif, Structure):
            structure = structure_or_cif
        else:
            # Assume CIF file
            structure = read_structure(structure_or_cif)

        structure = AbiStructure.asabistructure(structure)

        smearing = Smearing.assmearing(smearing)

        self._input_structure = structure

        v0 = structure.volume

        self.volumes = v0 * np.arange(90, 112, 2) / 100.

        for vol in self.volumes:

            new_lattice = structure.lattice.scale(vol)

            new_structure = Structure(new_lattice, structure.species,
                                      structure.frac_coords)
            new_structure = AbiStructure.asabistructure(new_structure)

            extra_abivars = {
                "ecutsm": ecutsm,
                "prtwf": 0,
            }
            if ecut is not None:
                extra_abivars.update({"ecut": ecut})

            ksampling = KSampling.automatic_density(new_structure,
                                                    kppa,
                                                    chksymbreak=chksymbreak)

            scf_strategy = ScfStrategy(new_structure,
                                       pseudos,
                                       ksampling,
                                       accuracy=accuracy,
                                       spin_mode=spin_mode,
                                       smearing=smearing,
                                       **extra_abivars)

            self.register_task(scf_strategy)
Exemplo n.º 20
0
def parse_view(args):
    from pymatgen.vis.structure_vtk import StructureVis
    excluded_bonding_elements = args.exclude_bonding[0].split(",") \
        if args.exclude_bonding else []
    s = read_structure(args.filename[0])
    vis = StructureVis(excluded_bonding_elements=excluded_bonding_elements)
    vis.set_structure(s)
    vis.show()
Exemplo n.º 21
0
 def setUp(self):
     with open(os.path.join(test_dir, "TiO2_entries.json"), 'r') as fp:
         entries = json.load(fp, cls=PMGJSONDecoder)
     self.struct_list = [e.structure for e in entries]
     self.oxi_structs = [
         read_structure(os.path.join(test_dir, fname))
         for fname in ["Li2O.cif", "POSCAR.Li2O"]
     ]
Exemplo n.º 22
0
 def test_read_structure(self):
     test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..",
                             'test_files')
     for fname in ("Li2O.cif", "Li2O2.cif", "vasprun.xml",
                   "vasprun_Si_bands.xml", "Si.cssr"):
         filename = os.path.join(test_dir, fname)
         struct = read_structure(filename)
         self.assertIsInstance(struct, Structure)
Exemplo n.º 23
0
def parse_view(args):
    from pymatgen.vis.structure_vtk import StructureVis
    excluded_bonding_elements = args.exclude_bonding[0].split(",") \
        if args.exclude_bonding else []
    s = read_structure(args.filename[0])
    vis = StructureVis(excluded_bonding_elements=excluded_bonding_elements)
    vis.set_structure(s)
    vis.show()
Exemplo n.º 24
0
 def test_read_structure(self):
     test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..",
                             'test_files')
     for fname in ("Li2O.cif", "Li2O2.cif", "vasprun.xml",
                   "vasprun_Si_bands.xml", "Si.cssr"):
         filename = os.path.join(test_dir, fname)
         struct = read_structure(filename)
         self.assertIsInstance(struct, Structure)
Exemplo n.º 25
0
def convert_fmt(args):
    iformat = args.input_format[0]
    oformat = args.output_format[0]
    filename = args.input_filename[0]
    out_filename = args.output_filename[0]

    try:
        if iformat == "smart":
            structure = read_structure(filename)
        if iformat == "POSCAR":
            p = Poscar.from_file(filename)
            structure = p.structure
        elif iformat == "CIF":
            r = CifParser(filename)
            structure = r.get_structures()[0]
        elif iformat == "CSSR":
            structure = Cssr.from_file(filename).structure

        if oformat == "smart":
            write_structure(structure, out_filename)
        elif oformat == "POSCAR":
            p = Poscar(structure)
            p.write_file(out_filename)
        elif oformat == "CIF":
            w = CifWriter(structure)
            w.write_file(out_filename)
        elif oformat == "CSSR":
            c = Cssr(structure)
            c.write_file(out_filename)
        elif oformat == "VASP":
            input_set = MPVaspInputSet()
            ts = TransformedStructure(structure, [],
                                      history=[{
                                          "source":
                                          "file",
                                          "datetime":
                                          str(datetime.datetime.now()),
                                          "original_file":
                                          open(filename).read()
                                      }])
            ts.write_vasp_input(input_set, output_dir=out_filename)
        elif oformat == "MITVASP":
            input_set = MITVaspInputSet()
            ts = TransformedStructure(structure, [],
                                      history=[{
                                          "source":
                                          "file",
                                          "datetime":
                                          str(datetime.datetime.now()),
                                          "original_file":
                                          open(filename).read()
                                      }])
            ts.write_vasp_input(input_set, output_dir=out_filename)

    except Exception as ex:
        print "Error converting file. Are they in the right format?"
        print str(ex)
Exemplo n.º 26
0
 def test_get_energy(self):
     m = IsingModel(5, 6)
     from pymatgen.core.periodic_table import Specie
     s = read_structure(os.path.join(test_dir, "LiFePO4.cif"))
     s.replace_species({"Fe": Specie("Fe", 2, {"spin": 4})})
     self.assertEqual(m.get_energy(s), 172.81260515787977)
     s[4] = Specie("Fe", 2, {"spin": -4})
     s[5] = Specie("Fe", 2, {"spin": -4})
     self.assertAlmostEqual(m.get_energy(s), 51.97424405382921)
Exemplo n.º 27
0
 def test_get_energy(self):
     m = IsingModel(5, 6)
     from pymatgen.core.periodic_table import Specie
     s = read_structure(os.path.join(test_dir, "LiFePO4.cif"))
     s.replace_species({"Fe": Specie("Fe", 2, {"spin": 4})})
     self.assertEqual(m.get_energy(s), 172.81260515787977)
     s.replace(4, Specie("Fe", 2, {"spin": -4}))
     s.replace(5, Specie("Fe", 2, {"spin": -4}))
     self.assertAlmostEqual(m.get_energy(s), 51.97424405382921)
Exemplo n.º 28
0
    def test_read_structure(self):
        test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..",
                                'test_files')
        for fname in ("Li2O.cif", "vasprun.xml", "vasprun_Si_bands.xml",
                      "Si.cssr"):
            filename = os.path.join(test_dir, fname)
            struct = read_structure(filename)
            self.assertIsInstance(struct, Structure)
            prim = read_structure(filename, primitive=True)
            self.assertLessEqual(len(prim), len(struct))
            sorted_s = read_structure(filename, sort=True)
            self.assertEqual(sorted_s, sorted_s.get_sorted_structure())

        m = StructureMatcher()
        for ext in [".cif", ".json", ".cssr"]:
            fn = "smartio_structure_test" + ext
            write_structure(struct, fn)
            back = read_structure(fn)
            self.assertTrue(m.fit(back, struct))
            os.remove(fn)
Exemplo n.º 29
0
    def test_read_structure(self):
        test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..",
                                'test_files')
        for fname in ("Li2O.cif", "vasprun.xml",
                      "vasprun_Si_bands.xml", "Si.cssr"):
            filename = os.path.join(test_dir, fname)
            struct = read_structure(filename)
            self.assertIsInstance(struct, Structure)
            prim = read_structure(filename, primitive=True)
            self.assertLessEqual(len(prim), len(struct))
            sorted_s = read_structure(filename, sort=True)
            self.assertEqual(sorted_s, sorted_s.get_sorted_structure())

        m = StructureMatcher()
        for ext in [".cif", ".json", ".cssr"]:
            fn = "smartio_structure_test" + ext
            write_structure(struct, fn)
            back = read_structure(fn)
            self.assertTrue(m.fit(back, struct))
            os.remove(fn)
Exemplo n.º 30
0
 def test_mix(self):
     structures = []
     for fname in ["POSCAR.Li2O", "Li2O.cif", "Li2O2.cif", "LiFePO4.cif", "POSCAR.LiFePO4"]:
         structures.append(read_structure(os.path.join(test_dir, fname)))
     sm = StructureMatcher(comparator=ElementComparator())
     groups = sm.group_structures(structures)
     for g in groups:
         formula = g[0].composition.reduced_formula
         if formula in ["Li2O", "LiFePO4"]:
             self.assertEqual(len(g), 2)
         else:
             self.assertEqual(len(g), 1)
Exemplo n.º 31
0
def convert_fmt(args):
    iformat = args.input_format[0]
    oformat = args.output_format[0]
    filename = args.input_filename[0]
    out_filename = args.output_filename[0]

    try:
        if iformat == "smart":
            structure = read_structure(filename)
        if iformat == "POSCAR":
            p = Poscar.from_file(filename)
            structure = p.structure
        elif iformat == "CIF":
            r = CifParser(filename)
            structure = r.get_structures()[0]
        elif iformat == "CSSR":
            structure = Cssr.from_file(filename).structure

        if oformat == "smart":
            write_structure(structure, out_filename)
        elif oformat == "POSCAR":
            p = Poscar(structure)
            p.write_file(out_filename)
        elif oformat == "CIF":
            w = CifWriter(structure)
            w.write_file(out_filename)
        elif oformat == "CSSR":
            c = Cssr(structure)
            c.write_file(out_filename)
        elif oformat == "VASP":
            input_set = MPVaspInputSet()
            ts = TransformedStructure(
                structure,
                [],
                history=[
                    {"source": "file", "datetime": str(datetime.datetime.now()), "original_file": open(filename).read()}
                ],
            )
            ts.write_vasp_input(input_set, output_dir=out_filename)
        elif oformat == "MITVASP":
            input_set = MITVaspInputSet()
            ts = TransformedStructure(
                structure,
                [],
                history=[
                    {"source": "file", "datetime": str(datetime.datetime.now()), "original_file": open(filename).read()}
                ],
            )
            ts.write_vasp_input(input_set, output_dir=out_filename)

    except Exception as ex:
        print "Error converting file. Are they in the right format?"
        print str(ex)
 def test_zero_spin_case(self):
     #ensure that zero spin case maintains sites and formula
     from pymatgen.io.smartio import read_structure
     s = read_structure(os.path.join(test_dir, 'Li2O.cif'))
     trans = MagOrderingTransformation({"Li+": 0.0}, 0.5)
     alls = trans.apply_transformation(s)
     #compositions will not be equal due to spin assignment
     #structure representations will be the same
     self.assertEqual(str(s), str(alls))
     #Ensure s does not have a spin property
     self.assertFalse('spin' in s.sites[0].specie._properties)
     #ensure sites are assigned a spin property in alls
     self.assertTrue('spin' in alls.sites[0].specie._properties)
Exemplo n.º 33
0
 def test_mix(self):
     structures = []
     for fname in ["POSCAR.Li2O", "Li2O.cif", "Li2O2.cif", "LiFePO4.cif",
                   "POSCAR.LiFePO4"]:
         structures.append(read_structure(os.path.join(test_dir, fname)))
     sm = StructureMatcher(comparator=ElementComparator())
     groups = sm.group_structures(structures)
     for g in groups:
         formula = g[0].composition.reduced_formula
         if formula in ["Li2O", "LiFePO4"]:
             self.assertEqual(len(g), 2)
         else:
             self.assertEqual(len(g), 1)
 def test_zero_spin_case(self):
     #ensure that zero spin case maintains sites and formula
     from pymatgen.io.smartio import read_structure
     s = read_structure(os.path.join(test_dir, 'Li2O.cif'))
     trans = MagOrderingTransformation({"Li+": 0.0}, 0.5)
     alls = trans.apply_transformation(s)
     #compositions will not be equal due to spin assignment
     #structure representations will be the same
     self.assertEqual(str(s), str(alls))
     #Ensure s does not have a spin property
     self.assertFalse('spin' in s.sites[0].specie._properties)
     #ensure sites are assigned a spin property in alls
     self.assertTrue('spin' in alls.sites[0].specie._properties)
Exemplo n.º 35
0
    def setup(self):
        """
        Performs initial setup for VaspJob, including overriding any settings
        and backing up.
        """
        files = os.listdir(".")
        num_structures = 0
        if not set(files).issuperset(VASP_INPUT_FILES):
            for f in files:
                try:
                    struct = read_structure(f)
                    num_structures += 1
                except:
                    pass
            if num_structures != 1:
                raise RuntimeError("{} structures found. Unable to continue."
                                   .format(num_structures))
            else:
                self.default_vis.write_input(struct, ".")

        if self.backup:
            for f in VASP_INPUT_FILES:
                shutil.copy(f, "{}.orig".format(f))

        if self.auto_npar:
            try:
                incar = Incar.from_file("INCAR")
                #Only optimized NPAR for non-HF and non-RPA calculations.
                if not (incar.get("LHFCALC") or incar.get("LRPA") or
                        incar.get("LEPSILON")):
                    if incar.get("IBRION") in [5, 6, 7, 8]:
                        # NPAR should not be set for Hessian matrix
                        # calculations, whether in DFPT or otherwise.
                        del incar["NPAR"]
                    else:
                        import multiprocessing
                        # try sge environment variable first
                        # (since multiprocessing counts cores on the current machine only)
                        ncores = os.environ.get('NSLOTS') or multiprocessing.cpu_count()
                        ncores = int(ncores)
                        for npar in range(int(round(math.sqrt(ncores))),
                                          ncores):
                            if ncores % npar == 0:
                                incar["NPAR"] = npar
                                break
                    incar.write_file("INCAR")
            except:
                pass

        if self.settings_override is not None:
            VaspModder().apply_actions(self.settings_override)
Exemplo n.º 36
0
def parse_symmetry(args):

    tolerance = float(args.tolerance[0])

    for filename in args.filenames:
        s = read_structure(filename)
        if args.spacegroup:
            finder = SymmetryFinder(s, tolerance)
            dataset = finder.get_symmetry_dataset()
            print filename
            print "Spacegroup  : {}".format(dataset["international"])
            print "Int number  : {}".format(dataset["number"])
            print "Hall symbol : {}".format(dataset["hall"])
            print
Exemplo n.º 37
0
def parse_symmetry(args):

    tolerance = float(args.tolerance[0])

    for filename in args.filenames:
        s = read_structure(filename)
        if args.spacegroup:
            finder = SymmetryFinder(s, tolerance)
            dataset = finder.get_symmetry_dataset()
            print filename
            print "Spacegroup  : {}".format(dataset["international"])
            print "Int number  : {}".format(dataset["number"])
            print "Hall symbol : {}".format(dataset["hall"])
            print
Exemplo n.º 38
0
    def setup(self):
        files = os.listdir(".")
        num_structures = 0
        if not set(files).issuperset(VASP_INPUT_FILES):
            for f in files:
                try:
                    struct = read_structure(f)
                    num_structures += 1
                except:
                    pass
            if num_structures != 1:
                raise RuntimeError("{} structures found. Unable to continue."
                                   .format(num_structures))
            else:
                self.default_vis.write_input(struct, ".")

        if self.backup:
            for f in VASP_INPUT_FILES:
                shutil.copy(f, "{}.orig".format(f))

        if self.auto_npar:
            try:
                vi = VaspInput.from_directory(".")
                incar = vi["INCAR"]
                #Only optimized NPAR for non-HF and non-RPA calculations.
                if (not incar.get("LHFCALC")) and (not incar.get("LRPA")):
                    import multiprocessing
                    ncores = multiprocessing.cpu_count()
                    for npar in range(int(round(math.sqrt(ncores))), ncores):
                        if ncores % npar == 0:
                            incar["NPAR"] = npar
                            break
                    incar.write_file("INCAR")
            except:
                pass

        if self.settings_override is not None:
            vi = VaspInput.from_directory(".")
            m = Modder([FileActions, DictActions])
            modified = []
            for a in self.settings_override:
                if "dict" in a:
                    modified.append(a["dict"])
                    vi[a["dict"]] = m.modify_object(a["action"],
                                                    vi[a["dict"]])
                elif "filename" in a:
                    m.modify(a["action"], a["filename"])
            for f in modified:
                vi[f].write_file(f)
Exemplo n.º 39
0
    def __init__(self, workdir, runmode, structure_or_cif, pseudos, kppa,
                 spin_mode="polarized", toldfe=1.e-8, smearing="fermi_dirac:0.1 eV",
                 accuracy="normal", ecut=None, ecutsm=0.05, chksymbreak=0): # FIXME Hack

        super(DeltaTest, self).__init__(workdir, runmode)

        if isinstance(structure_or_cif, Structure):
            structure = structure_or_cif
        else:
            # Assume CIF file
            structure = read_structure(structure_or_cif)

        structure = AbiStructure.asabistructure(structure)

        smearing = Smearing.assmearing(smearing)

        self._input_structure = structure

        v0 = structure.volume

        # From 94% to 106% of the equilibrium volume.
        self.volumes = v0 * np.arange(94, 108, 2) / 100.

        for vol in self.volumes:

            new_lattice = structure.lattice.scale(vol)

            new_structure = Structure(new_lattice, structure.species, structure.frac_coords)
            new_structure = AbiStructure.asabistructure(new_structure)

            extra_abivars = {
                "ecutsm": ecutsm,
                "toldfe": toldfe,
                "prtwf" : 0,
                "paral_kgb": 0,
            }

            if ecut is not None:
                extra_abivars.update({"ecut": ecut})

            ksampling = KSampling.automatic_density(new_structure, kppa,
                                                    chksymbreak=chksymbreak)

            scf_strategy = ScfStrategy(new_structure, pseudos, ksampling,
                                       accuracy=accuracy, spin_mode=spin_mode,
                                       smearing=smearing, **extra_abivars)

            self.register_task(scf_strategy)
Exemplo n.º 40
0
    def test_get_energy(self):
        coords = [[0, 0, 0], [0.75, 0.75, 0.75], [0.5, 0.5, 0.5],
                  [0.25, 0.25, 0.25]]
        lattice = Lattice([[3.0, 0.0, 0.0],
                           [1.0, 3.0, 0.00],
                           [0.00, -2.0, 3.0]])
        s = Structure(lattice,
                      [{"Si4+": 0.5, "O2-": 0.25, "P5+": 0.25},
                       {"Si4+": 0.5, "O2-": 0.25, "P5+": 0.25},
                       {"Si4+": 0.5, "O2-": 0.25, "P5+": 0.25},
                       {"Si4+": 0.5, "O2-": 0.25, "P5+": 0.25}], coords)

        m = EwaldElectrostaticModel()
        self.assertAlmostEqual(m.get_energy(s), 44.1070954178)
        s2 = read_structure(os.path.join(test_dir, "Li2O.cif"))
        self.assertAlmostEqual(m.get_energy(s2), -36.3476248117)
Exemplo n.º 41
0
    def test_get_energy(self):
        coords = [[0, 0, 0], [0.75, 0.75, 0.75], [0.5, 0.5, 0.5],
                  [0.25, 0.25, 0.25]]
        lattice = Lattice([[3.0, 0.0, 0.0],
                           [1.0, 3.0, 0.00],
                           [0.00, -2.0, 3.0]])
        s = Structure(lattice,
                      [{"Si4+": 0.5, "O2-": 0.25, "P5+": 0.25},
                       {"Si4+": 0.5, "O2-": 0.25, "P5+": 0.25},
                       {"Si4+": 0.5, "O2-": 0.25, "P5+": 0.25},
                       {"Si4+": 0.5, "O2-": 0.25, "P5+": 0.25}], coords)

        m = EwaldElectrostaticModel()
        self.assertAlmostEqual(m.get_energy(s), 44.1070954178)
        s2 = read_structure(os.path.join(test_dir, "Li2O.cif"))
        self.assertAlmostEqual(m.get_energy(s2), -36.3476248117)
Exemplo n.º 42
0
    def askopenfile_name(self):     
        """Returns an opened file in read mode.
        This time the dialog just returns a filename and the file is opened by your own code.
        """
        self.clear_text()
        
        #get filename
        file_name = tkFileDialog.askopenfilename(**self.file_opt)
        self.source = file_name
        if file_name == '' or file_name==():
            return
        self.cif_ent.insert(0, file_name)
        file_type = file_name.split(".")[-1]

        if file_type == 'cif':
            
            r = CifParser(self.source)
            self.fstruc = r.get_structures()[0]
            
        else:
            
            self.fstruc = read_structure(file_name)
Exemplo n.º 43
0
def convert_fmt(args):
    iformat = args.input_format[0]
    oformat = args.output_format[0]
    filename = args.input_filename[0]
    out_filename = args.output_filename[0]

    try:
        if iformat == "smart":
            structure = read_structure(filename)
        if iformat == "POSCAR":
            p = Poscar.from_file(filename)
            structure = p.structure
        elif iformat == "CIF":
            r = CifParser(filename)
            structure = r.get_structures()[0]
        elif iformat == "CSSR":
            structure = Cssr.from_file(filename).structure

        if oformat == "smart":
            write_structure(structure, out_filename)
        elif oformat == "POSCAR":
            p = Poscar(structure)
            p.write_file(out_filename)
        elif oformat == "CIF":
            w = CifWriter(structure)
            w.write_file(out_filename)
        elif oformat == "CSSR":
            c = Cssr(structure)
            c.write_file(out_filename)
        elif oformat == "VASP":
            input_set = MaterialsProjectVaspInputSet()
            transmuter = StandardTransmuter.from_structures([structure], [])
            transmuter.write_vasp_input(input_set, output_dir=out_filename)

    except Exception as ex:
        print "Error converting file. Are they in the right format?"
        print str(ex)
    def test_apply_transformation(self):
        trans = MagOrderingTransformation({"Fe": 5})
        p = Poscar.from_file(os.path.join(test_dir, 'POSCAR.LiFePO4'),
                             check_for_POTCAR=False)
        s = p.structure
        alls = trans.apply_transformation(s, 10)
        self.assertEqual(len(alls), 3)
        f = SymmetryFinder(alls[0]["structure"], 0.1)
        self.assertEqual(f.get_spacegroup_number(), 31)

        model = IsingModel(5, 5)
        trans = MagOrderingTransformation({"Fe": 5}, energy_model=model)
        alls2 = trans.apply_transformation(s, 10)
        #Ising model with +J penalizes similar neighbor magmom.
        self.assertNotEqual(alls[0]["structure"], alls2[0]["structure"])
        self.assertEqual(alls[0]["structure"], alls2[2]["structure"])

        from pymatgen.io.smartio import read_structure
        s = read_structure(os.path.join(test_dir, 'Li2O.cif'))
        #Li2O doesn't have magnetism of course, but this is to test the
        # enumeration.
        trans = MagOrderingTransformation({"Li+": 1}, max_cell_size=3)
        alls = trans.apply_transformation(s, 100)
        self.assertEqual(len(alls), 10)
Exemplo n.º 45
0
def finite_size_scale(standard, ssize, primordial, fsize, psize=[1, 1, 1]):
    """Function to perform finite size scaling for defect structure relaxation
    Inputs:
        standard = POSCAR file of structure containing defect
        ssize = Supercell size of structure with defect (list of size 3)
        primordial = POSCAR file of structure for basic unit of perfect cell
        psize = Supercell size of structure for padding. Default = [1,1,1] (list of size 3)
        fsize = Desired supercell size of final structure (list of size 3)
    Outputs:
        POSCAR file of structure containing defect and padding"""

    # Check if the input sizes work out with the desired final size
    padding = [0, 0, 0]
    for i in range(3):
        diff = fsize[i] - ssize[i]
        if diff < 0:
            raise RuntimeError(
                'Desired final size of the structure must be larger than \
existing defect structure size. Defect Size = ' + repr(ssize) +
                ' Final Size = ' + repr(fsize))
        elif diff >= 0:
            if math.fmod(diff, psize[i]):
                raise RuntimeError(
                    'Primordial structure and defect structure sizes cannot \
be used to form desired final size.  Reduce size of primordial structure. Defect Size = '
                    + repr(ssize) + ' Final Size = ' + repr(fsize) +
                    ' Primordial size = ' + repr(psize))
            else:
                padding[i] = diff / psize[i]

    # Load the defect structure and primordial structure
    try:
        defst = read_structure(standard)
    except:
        raise RuntimeError('Error: Unable to read standard structure.  Please check file. Filename: '+\
            standard)
    try:
        pst = read_structure(primordial)
    except:
        raise RuntimeError('Error: Unable to read primordial structure.  Please check file. Filename: '+\
            primordial)

    # Pad the structure
    positions = [site.coords for site in pst]
    syms = [str(site.specie.symbol) for site in pst]
    lv = [one / ssize for one in defst.lattice.matrix]
    vect = []
    for m0 in range(padding[0]):
        for m1 in numpy.arange(0, fsize[1], psize[1]):
            for m2 in numpy.arange(0, fsize[2], psize[2]):
                vect.append([ssize[0] + m0 * psize[0], m1, m2])

    for m1 in range(padding[1]):
        for m0 in numpy.arange(0, ssize[0], psize[0]):
            for m2 in numpy.arange(0, fsize[2], psize[2]):
                vect.append([m0, ssize[1] + m1 * psize[1], m2])

    for m2 in range(padding[2]):
        for m0 in numpy.arange(0, ssize[0], psize[0]):
            for m1 in numpy.arange(0, ssize[1], psize[1]):
                vect.append([m0, m1, ssize[2] + m2 * psize[2]])

    #Construct a new structure with desired size
    new_lat = Lattice(numpy.array([fsize[c] * lv[c] for c in range(3)]))
    final = Structure(new_lat,
                      defst.species_and_occu,
                      defst.cart_coords,
                      coords_are_cartesian=True)
    for m0, m1, m2 in vect:
        npos = positions + numpy.dot((m0, m1, m2), lv)
        for i in range(len(npos)):
            final.append(syms[i], npos[i], coords_are_cartesian=True)

    #Check for periodic issues in final structure
    final = check_periodic(final, defst)

    # Write output as POSCAR
    write_structure(final, 'POSCAR_Final')

    return final
Exemplo n.º 46
0
 def test_get_energy(self):
     m = SymmetryModel()
     s2 = read_structure(os.path.join(test_dir, "Li2O.cif"))
     self.assertEqual(m.get_energy(s2), -225)
Exemplo n.º 47
0
 def test_get_conversion_factor(self):
     filepath = os.path.join(test_dir, 'LiFePO4.cif')
     s = read_structure(filepath)
     self.assertAlmostEqual(41370704.1173,
                            get_conversion_factor(s, "Li", 600), 4)
Exemplo n.º 48
0
##############################################################
# This code is part of the MAterials Simulation Toolkit (MAST)
#
# Maintainer: Wei Xie
# Last updated: 2014-02-07
##############################################################
import sys, getopt, os
import shutil
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp

from pymatgen import Lattice, Structure
from pymatgen.io.smartio import read_structure, write_structure

stdX = read_structure("POSCAR_std")
prmX = read_structure("POSCAR_prm")
stdL = Structure.lattice(stdX)
prmL = Structure.lattice(stdX)


def finite_size_scale(standard, ssize, primordial, fsize, psize=[1, 1, 1]):
    """Function to perform finite size scaling for defect structure relaxation
    Inputs:
        standard = POSCAR file of structure containing defect
        ssize = Supercell size of structure with defect (list of size 3)
        primordial = POSCAR file of structure for basic unit of perfect cell
        psize = Supercell size of structure for padding. Default = [1,1,1] (list of size 3)
        fsize = Desired supercell size of final structure (list of size 3)
    Outputs:
        POSCAR file of structure containing defect and padding"""
Exemplo n.º 49
0
def get_structure_from_file(filename):
	return sio.read_structure(filename)
Exemplo n.º 50
0
 def setUp(self):
     with open(os.path.join(test_dir, "TiO2_entries.json"), 'r') as fp:
         entries = json.load(fp, cls=PMGJSONDecoder)
     self.struct_list = [e.structure for e in entries]
     self.oxi_structs = [read_structure(os.path.join(test_dir, fname))
                         for fname in ["Li2O.cif", "POSCAR.Li2O"]]
Exemplo n.º 51
0
 def test_left_handed_lattice(self):
     """Ensure Left handed lattices are accepted"""
     sm = StructureMatcher()
     s = read_structure(os.path.join(test_dir, "Li3GaPCO7.cif"))
     self.assertTrue(sm.fit(s, s))
 def test_get_conversion_factor(self):
     filepath = os.path.join(test_dir, 'LiFePO4.cif')
     s = read_structure(filepath)
     self.assertAlmostEqual(41370704.1173,
                            get_conversion_factor(s, "Li", 600), 4)
Exemplo n.º 53
0
 def test_get_energy(self):
     m = SymmetryModel()
     s2 = read_structure(os.path.join(test_dir, "Li2O.cif"))
     self.assertEqual(m.get_energy(s2), -225)
Exemplo n.º 54
0
 def test_left_handed_lattice(self):
     """Ensure Left handed lattices are accepted"""
     sm = StructureMatcher()
     s = read_structure(os.path.join(test_dir, "Li3GaPCO7.cif"))
     self.assertTrue(sm.fit(s, s))