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')})
    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_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)
    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))
Beispiel #5
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())
Beispiel #6
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.'
    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)
Beispiel #8
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))
Beispiel #9
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
    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)
Beispiel #11
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
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)
Beispiel #13
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)
Beispiel #14
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()
Beispiel #15
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)
Beispiel #16
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)
Beispiel #17
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_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)
Beispiel #20
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)
Beispiel #21
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
Beispiel #22
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)
Beispiel #23
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)
Beispiel #24
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)
Beispiel #25
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)
Beispiel #26
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)
Beispiel #27
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)
 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 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"]]
 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)