Ejemplo n.º 1
0
 def test_get_valence(self):
     parser = CifParser(os.path.join(test_dir, "LiMn2O4.cif"))
     s = parser.get_structures()[0]
     ans = [1, 1, 3, 3, 4, 4, -2, -2, -2, -2, -2, -2, -2, -2]
     self.assertEqual(self.analyzer.get_valences(s), ans)
     parser = CifParser(os.path.join(test_dir, "LiFePO4.cif"))
     s = parser.get_structures()[0]
     ans = [1, 1, 1, 1, 2, 2, 2, 2, 5, 5, 5, 5, -2, -2, -2, -2, -2, -2, -2,
            - 2, -2, -2, -2, -2, -2, -2, -2, -2]
     self.assertEqual(self.analyzer.get_valences(s), ans)
     parser = CifParser(os.path.join(test_dir, "Li3V2(PO4)3.cif"))
     s = parser.get_structures()[0]
     ans = [1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 5, 5, 5, 5, 5, 5, -2, -2, -2, -2,
            - 2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
            - 2, -2, -2, -2]
     self.assertEqual(self.analyzer.get_valences(s), ans)
     parser = CifParser(os.path.join(test_dir, "Li4Fe3Mn1(PO4)4.cif"))
     s = parser.get_structures()[0]
     ans = [1, 1, 1, 1, 2, 2, 2, 2, 5, 5, 5, 5, -2, -2, -2, -2, -2, -2, -2,
            - 2, -2, -2, -2, -2, -2, -2, -2, -2]
     self.assertEqual(self.analyzer.get_valences(s), ans)
     parser = CifParser(os.path.join(test_dir, "NaFePO4.cif"))
     s = parser.get_structures()[0]
     ans = [1, 1, 1, 1, 2, 2, 2, 2, 5, 5, 5, 5, -2, -2, -2, -2, -2, -2, -2,
            - 2, -2, -2, -2, -2, -2, -2, -2, -2]
     self.assertEqual(self.analyzer.get_valences(s), ans)
Ejemplo n.º 2
0
 def test_get_valence(self):
     parser = CifParser(os.path.join(test_dir, "LiMn2O4.cif"))
     s = parser.get_structures()[0]
     ans = [1, 1, 3, 3, 4, 4, -2, -2, -2, -2, -2, -2, -2, -2]
     self.assertEqual(self.analyzer.get_valences(s), ans)
     parser = CifParser(os.path.join(test_dir, "LiFePO4.cif"))
     s = parser.get_structures()[0]
     ans = [
         1, 1, 1, 1, 2, 2, 2, 2, 5, 5, 5, 5, -2, -2, -2, -2, -2, -2, -2, -2,
         -2, -2, -2, -2, -2, -2, -2, -2
     ]
     self.assertEqual(self.analyzer.get_valences(s), ans)
     parser = CifParser(os.path.join(test_dir, "Li3V2(PO4)3.cif"))
     s = parser.get_structures()[0]
     ans = [
         1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 5, 5, 5, 5, 5, 5, -2, -2, -2, -2, -2,
         -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
         -2, -2
     ]
     self.assertEqual(self.analyzer.get_valences(s), ans)
     parser = CifParser(os.path.join(test_dir, "Li4Fe3Mn1(PO4)4.cif"))
     s = parser.get_structures()[0]
     ans = [
         1, 1, 1, 1, 2, 2, 2, 2, 5, 5, 5, 5, -2, -2, -2, -2, -2, -2, -2, -2,
         -2, -2, -2, -2, -2, -2, -2, -2
     ]
     self.assertEqual(self.analyzer.get_valences(s), ans)
     parser = CifParser(os.path.join(test_dir, "NaFePO4.cif"))
     s = parser.get_structures()[0]
     ans = [
         1, 1, 1, 1, 2, 2, 2, 2, 5, 5, 5, 5, -2, -2, -2, -2, -2, -2, -2, -2,
         -2, -2, -2, -2, -2, -2, -2, -2
     ]
     self.assertEqual(self.analyzer.get_valences(s), ans)
Ejemplo n.º 3
0
    def test_init(self):
        fitter = StructureFitter(self.b, self.a)
        self.assertTrue(fitter.mapping_op != None, "No fit found!")

        #Now to try with rotated structure
        op = SymmOp.from_axis_angle_and_translation([0, 0, 1], 30, False, np.array([0, 0, 1]))
        editor = StructureEditor(self.a)
        editor.apply_operation(op)
        fitter = StructureFitter(self.b, editor.modified_structure)

        self.assertTrue(fitter.mapping_op != None, "No fit found!")

        #test with a supercell
        mod = SupercellMaker(self.a, scaling_matrix=[[2, 0, 0], [0, 1, 0], [0, 0, 1]])
        a_super = mod.modified_structure
        fitter = StructureFitter(self.b, a_super)
        self.assertTrue(fitter.mapping_op != None, "No fit found!")

        # Test with a structure with a translated point

        editor = StructureEditor(self.a)
        site = self.a[0]
        editor.delete_site(0)
        trans = np.random.randint(0, 1000, 3)
        editor.insert_site(0, site.species_and_occu, site.frac_coords + trans, False, False)
        fitter = StructureFitter(self.b, editor.modified_structure)
        self.assertTrue(fitter.mapping_op != None, "No fit found for translation {}!".format(trans))

        parser = CifParser(os.path.join(test_dir, "FePO4a.cif"))
        a = parser.get_structures()[0]
        parser = CifParser(os.path.join(test_dir, "FePO4b.cif"))
        b = parser.get_structures()[0]
        fitter = StructureFitter(b, a)
        self.assertTrue(fitter.mapping_op != None, "No fit found!")
Ejemplo n.º 4
0
    def test_init(self):
        if not enumlib_present:
            raise SkipTest("enumlib not present. Skipping...")
        test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..",
                                'test_files')
        parser = CifParser(os.path.join(test_dir, "LiFePO4.cif"))
        struct = parser.get_structures(False)[0]
        subtrans = SubstitutionTransformation({'Li': {'Li': 0.5}})
        adaptor = EnumlibAdaptor(subtrans.apply_transformation(struct), 1, 2)
        adaptor.run()
        structures = adaptor.structures
        self.assertEqual(len(structures), 86)
        for s in structures:
            self.assertAlmostEqual(s.composition
                                   .get_atomic_fraction(Element("Li")),
                                   0.5 / 6.5)
        adaptor = EnumlibAdaptor(subtrans.apply_transformation(struct), 1, 2,
                                 refine_structure=True)
        adaptor.run()
        structures = adaptor.structures
        self.assertEqual(len(structures), 52)

        subtrans = SubstitutionTransformation({'Li': {'Li': 0.25}})
        adaptor = EnumlibAdaptor(subtrans.apply_transformation(struct), 1, 1,
                                 refine_structure=True)
        adaptor.run()
        structures = adaptor.structures
        self.assertEqual(len(structures), 1)
        for s in structures:
            self.assertAlmostEqual(s.composition
                                   .get_atomic_fraction(Element("Li")),
                                   0.25 / 6.25)

        #Make sure it works for completely disordered structures.
        struct = Structure([[10, 0, 0], [0, 10, 0], [0, 0, 10]], [{'Fe':0.5}],
                           [[0, 0, 0]])
        adaptor = EnumlibAdaptor(struct, 1, 2)
        adaptor.run()
        self.assertEqual(len(adaptor.structures), 3)

        #Make sure it works properly when symmetry is broken by ordered sites.
        parser = CifParser(os.path.join(test_dir, "LiFePO4.cif"))
        struct = parser.get_structures(False)[0]
        subtrans = SubstitutionTransformation({'Li': {'Li': 0.25}})
        s = subtrans.apply_transformation(struct)
        #REmove some ordered sites to break symmetry.
        removetrans = RemoveSitesTransformation([4, 7])
        s = removetrans.apply_transformation(s)
        adaptor = EnumlibAdaptor(s, 1, 1, enum_precision_parameter=0.01)
        adaptor.run()
        structures = adaptor.structures
        self.assertEqual(len(structures), 4)

        struct = Structure([[3, 0, 0], [0, 3, 0], [0, 0, 3]],
                           [{"Si": 0.5}] * 2, [[0, 0, 0], [0.5, 0.5, 0.5]])
        adaptor = EnumlibAdaptor(struct, 1, 3, enum_precision_parameter=0.01)
        adaptor.run()
        structures = adaptor.structures
        self.assertEqual(len(structures), 10)
Ejemplo n.º 5
0
    def test_CifParser(self):
        parser = CifParser(os.path.join(test_dir, 'LiFePO4.cif'))
        for s in parser.get_structures(True):
            self.assertEqual(s.formula, "Li4 Fe4 P4 O16", "Incorrectly parsed cif.")

        #test for disordered structures
        parser = CifParser(os.path.join(test_dir, 'Li10GeP2S12.cif'))
        for s in parser.get_structures(True):
            self.assertEqual(s.formula, "Li20.2 Ge2.06 P3.94 S24", "Incorrectly parsed cif.")
Ejemplo n.º 6
0
 def test_anonymized_fitting(self):
     parser = CifParser(os.path.join(test_dir, "LiFePO4.cif"))
     a = parser.get_structures()[0]
     parser = CifParser(os.path.join(test_dir, "NaFePO4.cif"))
     b = parser.get_structures()[0]
     fitter = StructureFitter(b, a)
     self.assertTrue(fitter.mapping_op == None, "No fit should be found when NaFePO4 and LiFePo4 are fitted in non-anonymized mode!")
     fitter = StructureFitter(b, a, anonymized=True)
     self.assertTrue(fitter.mapping_op != None, "Fit should be found when NaFePO4 and LiFePo4 are fitted in anonymized mode!")
     self.assertEqual({el1.symbol:el2.symbol for el1, el2 in fitter.el_mapping.items()}, {"O":"O", "Fe":"Fe", "Na":"Li", "P":"P"})
Ejemplo n.º 7
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 = Structure.from_file(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 == "CONVENTIONAL_CIF":
            r = CifParser(filename)
            structure = r.get_structures(primitive=False)[0]
        elif iformat == "CSSR":
            structure = Cssr.from_file(filename).structure

        if oformat == "smart":
            structure.to(filename=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))
Ejemplo n.º 8
0
    def test_contains_peroxide(self):

        for filename in ['LiFePO4', 'NaFePO4', 'Li3V2(PO4)3', 'Li2O']:
            filepath = os.path.join(test_dir, "{}.cif".format(filename))
            parser = CifParser(filepath)
            s = parser.get_structures()[0]
            self.assertFalse(contains_peroxide(s))

        for filename in ['Li2O2', "K2O2"]:
            filepath = os.path.join(test_dir, "{}.cif".format(filename))
            parser = CifParser(filepath)
            s = parser.get_structures()[0]
            self.assertTrue(contains_peroxide(s))
Ejemplo n.º 9
0
    def test_contains_peroxide(self):

        for filename in ['LiFePO4', 'NaFePO4', 'Li3V2(PO4)3', 'Li2O']:
            filepath = os.path.join(test_dir, "{}.cif".format(filename))
            parser = CifParser(filepath)
            s = parser.get_structures()[0]
            self.assertFalse(contains_peroxide(s))

        for filename in ['Li2O2', "K2O2"]:
            filepath = os.path.join(test_dir, "{}.cif".format(filename))
            parser = CifParser(filepath)
            s = parser.get_structures()[0]
            self.assertTrue(contains_peroxide(s))
    def test_apply_transformation(self):
        t = PrimitiveCellTransformation()
        coords = list()
        coords.append([0, 0, 0])
        coords.append([0.375, 0.375, 0.375])
        coords.append([.5, .5, .5])
        coords.append([0.875, 0.875, 0.875])
        coords.append([0.125, 0.125, 0.125])
        coords.append([0.25, 0.25, 0.25])
        coords.append([0.625, 0.625, 0.625])
        coords.append([0.75, 0.75, 0.75])

        lattice = Lattice([[3.8401979337, 0.00, 0.00],
                           [1.9200989668, 3.3257101909, 0.00],
                           [0.00, -2.2171384943, 3.1355090603]])
        struct = Structure(
            lattice, ["Li+", "Li+", "Li+", "Li+", "O2-", "O2-", "O2-", "O2-"],
            coords)
        s = t.apply_transformation(struct)
        self.assertEqual(len(s), 4)

        parser = CifParser(os.path.join(test_dir, "TiO2_super.cif"))
        s = parser.get_structures()[0]
        prim = t.apply_transformation(s)
        self.assertEqual(prim.formula, "Ti4 O8")
Ejemplo n.º 11
0
 def setUp(self):
     p = Poscar.from_file(os.path.join(test_dir, 'POSCAR'))
     self.structure = p.structure
     self.sg = SymmetryFinder(self.structure, 0.001)
     parser = CifParser(os.path.join(test_dir, 'Li10GeP2S12.cif'))
     self.disordered_structure = parser.get_structures()[0]
     self.disordered_sg = SymmetryFinder(self.disordered_structure, 0.001)
     s = p.structure.copy()
     site = s[0]
     del s[0]
     s.append(site.species_and_occu, site.frac_coords)
     self.sg3 = SymmetryFinder(s, 0.001)
     parser = CifParser(os.path.join(test_dir, 'Graphite.cif'))
     graphite = parser.get_structures()[0]
     graphite.add_site_property("magmom", [0.1] * len(graphite))
     self.sg4 = SymmetryFinder(graphite, 0.001)
Ejemplo n.º 12
0
def read_structure(filename):
    """
    Reads a structure based on file extension. For example, anything ending in
    a "cif" is assumed to be a Crystallographic Information Format file.

    Args:
        filename:
            A filename to read from.

    Returns:
        A Structure object.
    """
    lower_filename = os.path.basename(filename).lower()
    if re.search("\.cif", lower_filename):
        parser = CifParser(filename)
        return parser.get_structures(True)[0]
    elif lower_filename.startswith("poscar") \
            or lower_filename.startswith("contcar"):
        return Poscar.from_file(filename, False).structure
    elif lower_filename.startswith("chgcar") \
            or lower_filename.startswith("locpot"):
        return Chgcar.from_file(filename).structure
    elif re.search("vasprun", lower_filename) \
            and re.search("xml", lower_filename):
        return Vasprun(filename).final_structure
    elif re.search("\.cssr", lower_filename):
        cssr = Cssr.from_file(filename)
        return cssr.structure

    raise ValueError("Unrecognized file extension!")
    def test_apply_transformation(self):
        t = PrimitiveCellTransformation()
        coords = list()
        coords.append([0, 0, 0])
        coords.append([0.375, 0.375, 0.375])
        coords.append([.5, .5, .5])
        coords.append([0.875, 0.875, 0.875])
        coords.append([0.125, 0.125, 0.125])
        coords.append([0.25, 0.25, 0.25])
        coords.append([0.625, 0.625, 0.625])
        coords.append([0.75, 0.75, 0.75])

        lattice = Lattice([[3.8401979337, 0.00, 0.00],
                           [1.9200989668, 3.3257101909, 0.00],
                           [0.00, -2.2171384943, 3.1355090603]])
        struct = Structure(lattice, ["Li+", "Li+", "Li+", "Li+",
                                     "O2-", "O2-", "O2-", "O2-"],
                           coords)
        s = t.apply_transformation(struct)
        self.assertEqual(len(s), 4)

        parser = CifParser(os.path.join(test_dir, "TiO2_super.cif"))
        s = parser.get_structures()[0]
        prim = t.apply_transformation(s)
        self.assertEqual(prim.formula, "Ti4 O8")
Ejemplo n.º 14
0
def read_structure(filename):
    """
    Reads a structure based on file extension. For example, anything ending in
    a "cif" is assumed to be a Crystallographic Information Format file.
    Supported formats include CIF, POSCAR/CONTCAR, CHGCAR, LOCPOT,
    vasprun.xml, CSSR and pymatgen's JSON serialized structures.

    Args:
        filename:
            A filename to read from.

    Returns:
        A Structure object.
    """
    fname = os.path.basename(filename)
    if fnmatch(fname.lower(), "*.cif*"):
        parser = CifParser(filename)
        return parser.get_structures(True)[0]
    elif fnmatch(fname, "POSCAR*") or fnmatch(fname, "CONTCAR*"):
        return Poscar.from_file(filename, False).structure
    elif fnmatch(fname, "CHGCAR*") or fnmatch(fname, "LOCPOT*"):
        return Chgcar.from_file(filename).structure
    elif fnmatch(fname, "vasprun*.xml*"):
        return Vasprun(filename).final_structure
    elif fnmatch(fname.lower(), "*.cssr*"):
        cssr = Cssr.from_file(filename)
        return cssr.structure
    elif fnmatch(fname, "*.json*") or fnmatch(fname, "*.mson*"):
        with zopen(filename) as f:
            s = json.load(f, cls=PMGJSONDecoder)
            if type(s) != Structure:
                raise IOError("File does not contain a valid serialized "
                              "structure")
            return s
    raise ValueError("Unrecognized file extension!")
Ejemplo n.º 15
0
def read_structure(filename):
    """
    Reads a structure based on file extension. For example, anything ending in
    a "cif" is assumed to be a Crystallographic Information Format file.
    Supported formats include CIF, POSCAR/CONTCAR, CHGCAR, LOCPOT,
    vasprun.xml, CSSR and pymatgen's JSON serialized structures.

    Args:
        filename (str): A filename to read from.

    Returns:
        A Structure object.
    """
    fname = os.path.basename(filename)
    if fnmatch(fname.lower(), "*.cif*"):
        parser = CifParser(filename)
        return parser.get_structures(True)[0]
    elif fnmatch(fname, "POSCAR*") or fnmatch(fname, "CONTCAR*"):
        return Poscar.from_file(filename, False).structure
    elif fnmatch(fname, "CHGCAR*") or fnmatch(fname, "LOCPOT*"):
        return Chgcar.from_file(filename).structure
    elif fnmatch(fname, "vasprun*.xml*"):
        return Vasprun(filename).final_structure
    elif fnmatch(fname.lower(), "*.cssr*"):
        cssr = Cssr.from_file(filename)
        return cssr.structure
    elif fnmatch(fname, "*.json*") or fnmatch(fname, "*.mson*"):
        with zopen(filename) as f:
            s = json.load(f, cls=PMGJSONDecoder)
            if type(s) != Structure:
                raise IOError("File does not contain a valid serialized "
                              "structure")
            return s
    raise ValueError("Unrecognized file extension!")
Ejemplo n.º 16
0
 def setUp(self):
     p = Poscar.from_file(os.path.join(test_dir, 'POSCAR'))
     self.structure = p.structure
     self.sg = SymmetryFinder(self.structure, 0.001)
     parser = CifParser(os.path.join(test_dir, 'Li10GeP2S12.cif'))
     self.disordered_structure = parser.get_structures()[0]
     self.disordered_sg = SymmetryFinder(self.disordered_structure, 0.001)
     s = p.structure.copy()
     site = s[0]
     del s[0]
     s.append(site.species_and_occu, site.frac_coords)
     self.sg3 = SymmetryFinder(s, 0.001)
     parser = CifParser(os.path.join(test_dir, 'Graphite.cif'))
     graphite = parser.get_structures()[0]
     graphite.add_site_property("magmom", [0.1] * len(graphite))
     self.sg4 = SymmetryFinder(graphite, 0.001)
Ejemplo n.º 17
0
 def setUp(self):
     p = Poscar.from_file(os.path.join(test_dir, 'POSCAR'))
     self.structure = p.structure
     self.sg = SymmetryFinder(self.structure, 0.001)
     parser = CifParser(os.path.join(test_dir, 'Li10GeP2S12.cif'))
     self.disordered_structure = parser.get_structures()[0]
     self.disordered_sg = SymmetryFinder(self.disordered_structure, 0.001)
     s = p.structure
     editor = StructureEditor(s)
     site = s[0]
     editor.delete_site(0)
     editor.append_site(site.species_and_occu, site.frac_coords)
     self.sg3 = SymmetryFinder(editor.modified_structure, 0.001)
     parser = CifParser(os.path.join(test_dir, 'Graphite.cif'))
     graphite = parser.get_structures()[0]
     self.sg4 = SymmetryFinder(graphite, 0.001)
Ejemplo n.º 18
0
 def setUp(self):
     """
     Setup Fe3O4  structure for testing multiple oxidation states
     """
     cif_ob = CifParser(os.path.join(test_dir, "Fe3O4.cif"))
     self._struct = cif_ob.get_structures()[0]
     self._valrad_evaluator = ValenceIonicRadiusEvaluator(self._struct)
     self._length = len(self._struct.sites)
Ejemplo n.º 19
0
 def setUp(self):
     """
     Setup Fe3O4  structure for testing multiple oxidation states
     """
     cif_ob = CifParser(os.path.join(test_dir, "Fe3O4.cif"))
     self._struct = cif_ob.get_structures()[0]
     self._valrad_evaluator = ValenceIonicRadiusEvaluator(self._struct)
     self._length = len(self._struct.sites)
Ejemplo n.º 20
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)
Ejemplo n.º 21
0
 def test_get_refined_structure(self):
     for a in self.sg.get_refined_structure().lattice.angles:
         self.assertEqual(a, 90)
     refined = self.disordered_sg.get_refined_structure()
     for a in refined.lattice.angles:
         self.assertEqual(a, 90)
     self.assertEqual(refined.lattice.a, refined.lattice.b)
     parser = CifParser(os.path.join(test_dir, 'Li2O.cif'))
     s = parser.get_structures()[0]
     sg = SymmetryFinder(s, 0.001)
     self.assertEqual(sg.get_refined_structure().num_sites, 4 * s.num_sites)
Ejemplo n.º 22
0
def ConvertCifFileToPoscarFile(cifFilename,poscarFilename):
  parser = CifParser(cifFilename)
  structure = parser.get_structures()[0]
  structure_name = cif_file.split('.')[0]

  poscar_obj      = Poscar(structure=structure,comment=structure_name)
  poscar_string   = poscar_obj.to_string()
  poscar_filename = '{}/{}.poscar'.format(poscar_directory_name,structure_name)

  with open(poscar_filename,'w') as f:
    f.write(poscar_string)
Ejemplo n.º 23
0
 def test_get_refined_structure(self):
     for a in self.sg.get_refined_structure().lattice.angles:
         self.assertEqual(a, 90)
     refined = self.disordered_sg.get_refined_structure()
     for a in refined.lattice.angles:
         self.assertEqual(a, 90)
     self.assertEqual(refined.lattice.a, refined.lattice.b)
     parser = CifParser(os.path.join(test_dir, 'Li2O.cif'))
     s = parser.get_structures()[0]
     sg = SymmetryFinder(s, 0.001)
     self.assertEqual(sg.get_refined_structure().num_sites, 4 * s.num_sites)
Ejemplo n.º 24
0
 def test_filter(self):
     filename = os.path.join(test_dir, "Li10GeP2S12.cif")
     p = CifParser(filename)
     s = p.get_structures()[0]
     sf = SpecieProximityFilter({"Li": 1})
     self.assertTrue(sf.test(s))
     sf = SpecieProximityFilter({"Li": 2})
     self.assertFalse(sf.test(s))
     sf = SpecieProximityFilter({"P": 1})
     self.assertTrue(sf.test(s))
     sf = SpecieProximityFilter({"P": 5})
     self.assertFalse(sf.test(s))
Ejemplo n.º 25
0
 def test_filter(self):
     filename = os.path.join(test_dir, "Li10GeP2S12.cif")
     p = CifParser(filename)
     s = p.get_structures()[0]
     sf = SpecieProximityFilter({"Li": 1})
     self.assertTrue(sf.test(s))
     sf = SpecieProximityFilter({"Li": 2})
     self.assertFalse(sf.test(s))
     sf = SpecieProximityFilter({"P": 1})
     self.assertTrue(sf.test(s))
     sf = SpecieProximityFilter({"P": 5})
     self.assertFalse(sf.test(s))
Ejemplo n.º 26
0
 def test_find_primitive(self):
     """
     F m -3 m Li2O testing of converting to primitive cell
     """
     parser = CifParser(os.path.join(test_dir, 'Li2O.cif'))
     structure = parser.get_structures(False)[0]
     s = SymmetryFinder(structure)
     primitive_structure = s.find_primitive()
     self.assertEqual(primitive_structure.formula, "Li2 O1")
     # This isn't what is expected. All the angles should be 60
     self.assertAlmostEqual(primitive_structure.lattice.alpha, 60)
     self.assertAlmostEqual(primitive_structure.lattice.beta, 60)
     self.assertAlmostEqual(primitive_structure.lattice.gamma, 60)
     self.assertAlmostEqual(primitive_structure.lattice.volume,
                            structure.lattice.volume / 4.0)
Ejemplo n.º 27
0
 def test_get_primitive(self):
     """
     F m -3 m Li2O testing of converting to primitive cell
     """
     self.assertIsNone(self.sg.find_primitive())
     parser = CifParser(os.path.join(test_dir, 'Li2O.cif'))
     structure = parser.get_structures(False)[0]
     s = SymmetryFinder(structure)
     primitive_structure = s.find_primitive()
     self.assertEqual(primitive_structure.formula, "Li2 O1")
     # This isn't what is expected. All the angles should be 60
     self.assertAlmostEqual(primitive_structure.lattice.alpha, 120)
     self.assertAlmostEqual(primitive_structure.lattice.beta, 60)
     self.assertAlmostEqual(primitive_structure.lattice.gamma, 120)
     self.assertAlmostEqual(primitive_structure.lattice.volume, structure.lattice.volume / 4.0)
Ejemplo n.º 28
0
    def from_cif_file(cif_file):

        """
        Static method to create Header object from cif_file

        Arg:
            cif_file:
                cif_file path and name
        Returns:
            Header Object

        """
        r = CifParser(cif_file)
        structure = r.get_structures()[0]

        return Header(structure)
Ejemplo n.º 29
0
    def from_cif_file(cif_file, source='', comment=''):
        """
        Static method to create Header object from cif_file

        Args:
            cif_file: cif_file path and name
            source: User supplied identifier, i.e. for Materials Project this
                would be the material ID number
            comment: User comment that goes in header

        Returns:
            Header Object
        """
        r = CifParser(cif_file)
        structure = r.get_structures()[0]
        return Header(structure, source, comment)
Ejemplo n.º 30
0
    def from_cif_file(cif_file, source='', comment=''):
        """
        Static method to create Header object from cif_file

        Args:
            cif_file: cif_file path and name
            source: User supplied identifier, i.e. for Materials Project this
                would be the material ID number
            comment: User comment that goes in header

        Returns:
            Header Object
        """
        r = CifParser(cif_file)
        structure = r.get_structures()[0]
        return Header(structure, source, comment)
Ejemplo n.º 31
0
def cif2geom(ciffile):
  parser=CifParser(ciffile)
  struct=parser.get_structures()[0]
  primstruct=struct.get_primitive_structure()
  lat=primstruct.as_dict()['lattice']
  sites=primstruct.as_dict()['sites']
  geomlines=["CRYSTAL","0 0 0","1","%g %g %g %g %g %g"%\
          (lat['a'],lat['b'],lat['c'],lat['alpha'],lat['beta'],lat['gamma'])]

  geomlines+=["%i"%len(sites)]
  for v in sites:
      nm=v['species'][0]['element']
      nm=str(Element(nm).Z+200)
      geomlines+=[nm+" %g %g %g"%(v['abc'][0],v['abc'][1],v['abc'][2])]

  return geomlines,primstruct
Ejemplo n.º 32
0
def _get_aiida_structure_pymatgen_inline(cif=None, parameters=None):
    """
    Creates :py:class:`aiida.orm.data.structure.StructureData` using
    pymatgen.

    .. note:: requires pymatgen module.
    """
    from pymatgen.io.cifio import CifParser
    from aiida.orm.data.structure import StructureData

    kwargs = {}
    if parameters is not None:
        kwargs = parameters.get_dict()
    kwargs['primitive'] = kwargs.pop('primitive_cell', False)
    parser = CifParser(cif.get_file_abs_path())
    try:
        struct = parser.get_structures(**kwargs)[0]
        return {'structure': StructureData(pymatgen_structure=struct)}
    except IndexError:
        raise ValueError("pymatgen failed to provide a structure from the cif file")
Ejemplo n.º 33
0
def read_structure(filename, primitive=True, sort=False):
    """
    Reads a structure based on file extension. For example, anything ending in
    a "cif" is assumed to be a Crystallographic Information Format file.
    Supported formats include CIF, POSCAR/CONTCAR, CHGCAR, LOCPOT,
    vasprun.xml, CSSR and pymatgen's JSON serialized structures.

    Args:
        filename (str): A filename to read from.
        primitive (bool): Whether to convert to a primitive cell for cifs.
            Defaults to False.
        sort (bool): Whether to sort sites. Default to False.

    Returns:
        A Structure object.
    """
    fname = os.path.basename(filename)
    if fnmatch(fname.lower(), "*.cif*"):
        parser = CifParser(filename)
        s = parser.get_structures(primitive=primitive)[0]
    elif fnmatch(fname, "POSCAR*") or fnmatch(fname, "CONTCAR*"):
        s = Poscar.from_file(filename, False).structure
    elif fnmatch(fname, "CHGCAR*") or fnmatch(fname, "LOCPOT*"):
        s = Chgcar.from_file(filename).structure
    elif fnmatch(fname, "vasprun*.xml*"):
        s = Vasprun(filename).final_structure
    elif fnmatch(fname.lower(), "*.cssr*"):
        cssr = Cssr.from_file(filename)
        s = cssr.structure
    elif fnmatch(fname, "*.json*") or fnmatch(fname, "*.mson*"):
        with zopen(filename) as f:
            s = json.load(f, cls=PMGJSONDecoder)
            if type(s) != Structure:
                raise IOError("File does not contain a valid serialized "
                              "structure")
    else:
        raise ValueError("Unrecognized file extension!")
    if sort:
        s = s.get_sorted_structure()
    return s
Ejemplo n.º 34
0
def read_structure(filename, primitive=True, sort=False):
    """
    Reads a structure based on file extension. For example, anything ending in
    a "cif" is assumed to be a Crystallographic Information Format file.
    Supported formats include CIF, POSCAR/CONTCAR, CHGCAR, LOCPOT,
    vasprun.xml, CSSR and pymatgen's JSON serialized structures.

    Args:
        filename (str): A filename to read from.
        primitive (bool): Whether to convert to a primitive cell for cifs.
            Defaults to True.
        sort (bool): Whether to sort sites. Default to False.

    Returns:
        A Structure object.
    """
    fname = os.path.basename(filename)
    if fnmatch(fname.lower(), "*.cif*"):
        parser = CifParser(filename)
        s = parser.get_structures(primitive=primitive)[0]
    elif fnmatch(fname, "POSCAR*") or fnmatch(fname, "CONTCAR*"):
        s = Poscar.from_file(filename, False).structure
    elif fnmatch(fname, "CHGCAR*") or fnmatch(fname, "LOCPOT*"):
        s = Chgcar.from_file(filename).structure
    elif fnmatch(fname, "vasprun*.xml*"):
        s = Vasprun(filename).final_structure
    elif fnmatch(fname.lower(), "*.cssr*"):
        cssr = Cssr.from_file(filename)
        s = cssr.structure
    elif fnmatch(fname, "*.json*") or fnmatch(fname, "*.mson*"):
        with zopen(filename) as f:
            s = json.load(f, cls=MontyDecoder)
            if type(s) != Structure:
                raise IOError("File does not contain a valid serialized "
                              "structure")
    else:
        raise ValueError("Unrecognized file extension!")
    if sort:
        s = s.get_sorted_structure()
    return s
Ejemplo n.º 35
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)
Ejemplo n.º 36
0
def read_structure(filename):
    """
    Reads a structure based on file extension. For example, anything ending in
    a "cif" is assumed to be a Crystallographic Information Format file.
    Supported formats include CIF, POSCAR/CONTCAR, CHGCAR, LOCPOT,
    vasprun.xml, CSSR and pymatgen's JSON serialized structures.

    Args:
        filename:
            A filename to read from.

    Returns:
        A Structure object.
    """
    lower_filename = os.path.basename(filename).lower()
    if re.search("\.cif", lower_filename):
        parser = CifParser(filename)
        return parser.get_structures(True)[0]
    elif lower_filename.startswith("poscar") \
            or lower_filename.startswith("contcar"):
        return Poscar.from_file(filename, False).structure
    elif lower_filename.startswith("chgcar") \
            or lower_filename.startswith("locpot"):
        return Chgcar.from_file(filename).structure
    elif re.search("vasprun", lower_filename) \
            and re.search("xml", lower_filename):
        return Vasprun(filename).final_structure
    elif re.search("\.cssr", lower_filename):
        cssr = Cssr.from_file(filename)
        return cssr.structure
    elif re.search("\.[mj]son", lower_filename):
        with zopen(lower_filename) as f:
            s = json.load(f, cls=PMGJSONDecoder)
            if type(s) != Structure:
                raise IOError("File does not contain a valid serialized "
                              "structure")
            return s

    raise ValueError("Unrecognized file extension!")
Ejemplo n.º 37
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)
Ejemplo n.º 38
0
def move_atom(input_cif, output_cif, atom_idx, displacement_vec):
    """ 
  Reads input cif (as file name), moves atom by displacement vector (in
  angstroms), and writes to output_cif (as file name).

  Currently, doesn't take into account the symmetry operations. This is
  theoretically possible with PyMatGen, although I found it to be buggy so
  decided it might not be worth it. 
  Useful things to look up for implementing this:

  pymatgen.symmetry.analyzer.SpacegroupAnalyzer.get_symmetrized_structure

  and its resulting method

  find_equivalent_sites()
  """
    parser = CifParser(input_cif)
    struct = parser.get_structures()[0]
    lat_const = np.array(struct.lattice.abc)
    frac_pos = struct[atom_idx].frac_coords
    new_pos = frac_pos + displacement_vec / lat_const
    struct[atom_idx] = struct[atom_idx].species_and_occu.elements[0], new_pos
    writer = CifWriter(struct)
    writer.write_file(output_cif)
Ejemplo n.º 39
0
def move_atom(input_cif, output_cif, atom_idx, displacement_vec):
  """ 
  Reads input cif (as file name), moves atom by displacement vector (in
  angstroms), and writes to output_cif (as file name).

  Currently, doesn't take into account the symmetry operations. This is
  theoretically possible with PyMatGen, although I found it to be buggy so
  decided it might not be worth it. 
  Useful things to look up for implementing this:

  pymatgen.symmetry.analyzer.SpacegroupAnalyzer.get_symmetrized_structure

  and its resulting method

  find_equivalent_sites()
  """
  parser    = CifParser(input_cif)
  struct    = parser.get_structures()[0]
  lat_const = np.array(struct.lattice.abc)
  frac_pos  = struct[atom_idx].frac_coords
  new_pos   = frac_pos + displacement_vec/lat_const
  struct[atom_idx] = struct[atom_idx].species_and_occu.elements[0], new_pos
  writer = CifWriter(struct)
  writer.write_file(output_cif)
        else:
            file_format = 'cif'
    else:
        file_format = 'poscar'

    isomer_count = {'cis': 0, 'trans': 0, 'fac': 0, 'mer': 0, 'mixed': 0}
    for entry in structures_list:
        struct_name = entry.replace("{}-".format(dictionary), '')
        struct_name = struct_name.replace('.vasp', '')
        #print struct_name
        if file_format == 'poscar':
            poscar = Poscar.from_file(entry)
            struct = poscar.structure
        elif file_format == 'cif':
            parser = CifParser(entry)
            struct = parser.get_structures()[0]
        #cations_indx = [0,3,5,6]
        if len(cations_indx) == 0:
            cations_indx = struct.indices_from_symbol(cati)

        anions_indx = struct.indices_from_symbol(ani)

        cation_neighs = dict()
        ordering_rank = []
        for cation in cations_indx:
            myneigh = []
            for anion in anions_indx:
                distance = struct.get_distance(cation, anion)
                if distance <= cutoff:
                    myneigh.append(anion)
            ordering_rank.append(len(myneigh))
Ejemplo n.º 41
0
 def setUp(self):
     filepath = os.path.join(test_dir, 'LiFePO4.cif')
     parser = CifParser(filepath)
     s = parser.get_structures()[0]
     self.finder = VoronoiCoordFinder(s, [Element("O")])
Ejemplo n.º 42
0
parser.add_argument('-f', '--format', dest='format', type=str, nargs=1, choices=['cif', 'poscar'], default='poscar', help='Format of input file. Defaults to POSCAR')
parser.add_argument('-t', '--tolerance', dest='tolerance', type=float, nargs=1, help='Tolerance for symmetry determination')

args = parser.parse_args()
tolerance = float(args.tolerance[0]) if args.tolerance else 0.1

file_format = args.format

if args.input_file[0].lower().endswith(".cif"):
    file_format = "cif"
elif args.input_file[0].upper().startswith("POSCAR"):
    file_format = "poscar"

s = None

if file_format == 'poscar':
    p = Poscar.from_file(args.input_file[0])
    s = p.struct
else:
    r = CifParser(args.input_file[0])
    s = r.get_structures(False)[0]

if s:
    finder = SymmetryFinder(s, tolerance)
    dataset = finder.get_symmetry_dataset()
    print "Spacegroup  : {}".format(dataset['international'])
    print "Int number  : {}".format(dataset['number'])
    print "Hall symbol : {}".format(dataset["hall"])

Ejemplo n.º 43
0
 def setUp(self):
     filepath = os.path.join(test_dir, 'LiFePO4.cif')
     parser = CifParser(filepath)
     self.s = parser.get_structures()[0]
Ejemplo n.º 44
0
    def test_init(self):
        test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..",
                                'test_files')
        parser = CifParser(os.path.join(test_dir, "LiFePO4.cif"))
        struct = parser.get_structures(False)[0]
        subtrans = SubstitutionTransformation({'Li': {'Li': 0.5}})
        adaptor = EnumlibAdaptor(subtrans.apply_transformation(struct), 1, 2)
        adaptor.run()
        structures = adaptor.structures
        self.assertEqual(len(structures), 86)
        for s in structures:
            self.assertAlmostEqual(
                s.composition.get_atomic_fraction(Element("Li")), 0.5 / 6.5)
        adaptor = EnumlibAdaptor(subtrans.apply_transformation(struct),
                                 1,
                                 2,
                                 refine_structure=True)
        adaptor.run()
        structures = adaptor.structures
        self.assertEqual(len(structures), 52)

        subtrans = SubstitutionTransformation({'Li': {'Li': 0.25}})
        adaptor = EnumlibAdaptor(subtrans.apply_transformation(struct),
                                 1,
                                 1,
                                 refine_structure=True)
        adaptor.run()
        structures = adaptor.structures
        self.assertEqual(len(structures), 1)
        for s in structures:
            self.assertAlmostEqual(
                s.composition.get_atomic_fraction(Element("Li")), 0.25 / 6.25)

        #Make sure it works for completely disordered structures.
        struct = Structure([[10, 0, 0], [0, 10, 0], [0, 0, 10]], [{
            'Fe': 0.5
        }], [[0, 0, 0]])
        adaptor = EnumlibAdaptor(struct, 1, 2)
        adaptor.run()
        self.assertEqual(len(adaptor.structures), 3)

        #Make sure it works properly when symmetry is broken by ordered sites.
        parser = CifParser(os.path.join(test_dir, "LiFePO4.cif"))
        struct = parser.get_structures(False)[0]
        subtrans = SubstitutionTransformation({'Li': {'Li': 0.25}})
        s = subtrans.apply_transformation(struct)
        #REmove some ordered sites to break symmetry.
        removetrans = RemoveSitesTransformation([4, 7])
        s = removetrans.apply_transformation(s)
        adaptor = EnumlibAdaptor(s, 1, 1, enum_precision_parameter=0.01)
        adaptor.run()
        structures = adaptor.structures
        self.assertEqual(len(structures), 4)

        struct = Structure([[3, 0, 0], [0, 3, 0], [0, 0, 3]], [{
            "Si": 0.5
        }] * 2, [[0, 0, 0], [0.5, 0.5, 0.5]])
        adaptor = EnumlibAdaptor(struct, 1, 3, enum_precision_parameter=0.01)
        adaptor.run()
        structures = adaptor.structures
        self.assertEqual(len(structures), 10)
Ejemplo n.º 45
0
    def test_CifParser(self):
        parser = CifParser(os.path.join(test_dir, 'LiFePO4.cif'))
        for s in parser.get_structures(True):
            self.assertEqual(s.formula, "Li4 Fe4 P4 O16",
                             "Incorrectly parsed cif.")

        parser = CifParser(os.path.join(test_dir, 'V2O3.cif'))
        for s in parser.get_structures(True):
            self.assertEqual(s.formula, "V4 O6")

        parser = CifParser(os.path.join(test_dir, 'Li2O.cif'))
        prim = parser.get_structures(True)[0]
        self.assertEqual(prim.formula, "Li2 O1")
        conv = parser.get_structures(False)[0]
        self.assertEqual(conv.formula, "Li8 O4")

        #test for disordered structures
        parser = CifParser(os.path.join(test_dir, 'Li10GeP2S12.cif'))
        for s in parser.get_structures(True):
            self.assertEqual(s.formula, "Li20.2 Ge2.06 P3.94 S24",
                             "Incorrectly parsed cif.")
        cif_str = """#\#CIF1.1
##########################################################################
#               Crystallographic Information Format file
#               Produced by PyCifRW module
#
#  This is a CIF file.  CIF has been adopted by the International
#  Union of Crystallography as the standard for data archiving and
#  transmission.
#
#  For information on this file format, follow the CIF links at
#  http://www.iucr.org
##########################################################################

data_FePO4
_symmetry_space_group_name_H-M          'P 1'
_cell_length_a                          10.4117668699
_cell_length_b                          6.06717187997
_cell_length_c                          4.75948953998
_cell_angle_alpha                       90.0
_cell_angle_beta                        90.0
_cell_angle_gamma                       90.0
_chemical_name_systematic               'Generated by pymatgen'
_symmetry_Int_Tables_number             1
_chemical_formula_structural            FePO4
_chemical_formula_sum                   'Fe4 P4 O16'
_cell_volume                            300.65685512
_cell_formula_units_Z                   4
loop_
  _symmetry_equiv_pos_site_id
  _symmetry_equiv_pos_as_xyz
   1  'x, y, z'

loop_
  _atom_site_type_symbol
  _atom_site_label
  _atom_site_symmetry_multiplicity
  _atom_site_fract_x
  _atom_site_fract_y
  _atom_site_fract_z
  _atom_site_attached_hydrogens
  _atom_site_B_iso_or_equiv
  _atom_site_occupancy
   Fe  Fe1  1  0.218728  0.750000  0.474867  0  .  1
   Fe  Fe2  1  0.281272  0.250000  0.974867  0  .  1
   Fe  Fe3  1  0.718728  0.750000  0.025133  0  .  1
   Fe  Fe4  1  0.781272  0.250000  0.525133  0  .  1
   P  P5  1  0.094613  0.250000  0.418243  0  .  1
   P  P6  1  0.405387  0.750000  0.918243  0  .  1
   P  P7  1  0.594613  0.250000  0.081757  0  .  1
   P  P8  1  0.905387  0.750000  0.581757  0  .  1
   O  O9  1  0.043372  0.750000  0.707138  0  .  1
   O  O10  1  0.096642  0.250000  0.741320  0  .  1
   O  O11  1  0.165710  0.046072  0.285384  0  .  1
   O  O12  1  0.165710  0.453928  0.285384  0  .  1
   O  O13  1  0.334290  0.546072  0.785384  0  .  1
   O  O14  1  0.334290  0.953928  0.785384  0  .  1
   O  O15  1  0.403358  0.750000  0.241320  0  .  1
   O  O16  1  0.456628  0.250000  0.207138  0  .  1
   O  O17  1  0.543372  0.750000  0.792862  0  .  1
   O  O18  1  0.596642  0.250000  0.758680  0  .  1
   O  O19  1  0.665710  0.046072  0.214616  0  .  1
   O  O20  1  0.665710  0.453928  0.214616  0  .  1
   O  O21  1  0.834290  0.546072  0.714616  0  .  1
   O  O22  1  0.834290  0.953928  0.714616  0  .  1
   O  O23  1  0.903358  0.750000  0.258680  0  .  1
   O  O24  1  0.956628  0.250000  0.292862  0  .  1

"""
        parser = CifParser.from_string(cif_str)
        self.assertEqual(parser.get_structures()[0].formula, "Fe4 P4 O16",
                         "Incorrectly parsed cif.")

        parser = CifParser(os.path.join(test_dir, 'srycoo.cif'))
        self.assertEqual(parser.get_structures()[0].formula,
                         "Sr5.6 Y2.4 Co8 O21")
Ejemplo n.º 46
0
  structure = parser.get_structures()[0]
  structure_name = cif_file.split('.')[0]

  poscar_obj      = Poscar(structure=structure,comment=structure_name)
  poscar_string   = poscar_obj.to_string()
  poscar_filename = '{}/{}.poscar'.format(poscar_directory_name,structure_name)

  with open(poscar_filename,'w') as f:
    f.write(poscar_string)

#------------------------------------------------------------------------------
cif_filenames = GetFilenamesInDirectory(directoryName=cif_directory_name)
crystal_system_names = [cif_filename.split('.')[0] for cif_filename in cif_filenames]

EnsureDirectoryExists(directoryName=poscar_directory_name)
for cif_file in cif_filenames:
  cif_filename   = "{}/{}".format(cif_directory_name,cif_file)
  structure_name = cif_file.split('.')[0]

  # Parse .cif file into a pymatgen structure file
  parser    = CifParser(cif_filename)
  structure = parser.get_structures()[0]

  # Create the poscar object and write it to file
  poscar_obj      = Poscar(structure=structure,comment=structure_name)
  poscar_string   = poscar_obj.get_string()
  poscar_filename = '{}/{}.poscar'.format(poscar_directory_name,structure_name)
  with open(poscar_filename,'w') as f:
    f.write(poscar_string)

Ejemplo n.º 47
0
 def test_get_oxi_state_structure(self):
     parser = CifParser(os.path.join(test_dir, "LiMn2O4.cif"))
     s = parser.get_structures()[0]
     news = self.analyzer.get_oxi_state_decorated_structure(s)
     self.assertIn(Specie("Mn", 3), news.composition.elements)
     self.assertIn(Specie("Mn", 4), news.composition.elements)
Ejemplo n.º 48
0
 def test_primes(self):
     parser = CifParser(os.path.join(test_dir, 'C26H16BeN2O2S2.cif'))
     for s in parser.get_structures(False):
         self.assertEqual(s.composition, 8 * Composition('C26H16BeN2O2S2'))
Ejemplo n.º 49
0
 def test_get_oxi_state_structure(self):
     parser = CifParser(os.path.join(test_dir, "LiMn2O4.cif"))
     s = parser.get_structures()[0]
     news = self.analyzer.get_oxi_state_decorated_structure(s)
     self.assertIn(Specie("Mn", 3), news.composition.elements)
     self.assertIn(Specie("Mn", 4), news.composition.elements)
Ejemplo n.º 50
0
 def test_missing_atom_site_type_with_oxistates(self):
     parser = CifParser(os.path.join(test_dir, 'P24Ru4H252C296S24N16.cif'))
     c = Composition({'S0+': 24, 'Ru0+': 4, 'H0+': 252, 'C0+': 296,
                      'N0+': 16, 'P0+': 24})
     for s in parser.get_structures(False):
         self.assertEqual(s.composition, c)
Ejemplo n.º 51
0
    def test_get_primitive_standard_structure(self):
        parser = CifParser(os.path.join(test_dir, 'bcc_1927.cif'))
        structure = parser.get_structures(False)[0]
        s = SpacegroupAnalyzer(structure, symprec=1e-2)
        prim = s.get_primitive_standard_structure()
        self.assertAlmostEqual(prim.lattice.alpha, 109.47122063400001)
        self.assertAlmostEqual(prim.lattice.beta, 109.47122063400001)
        self.assertAlmostEqual(prim.lattice.gamma, 109.47122063400001)
        self.assertAlmostEqual(prim.lattice.a, 7.9657251015812145)
        self.assertAlmostEqual(prim.lattice.b, 7.9657251015812145)
        self.assertAlmostEqual(prim.lattice.c, 7.9657251015812145)

        parser = CifParser(os.path.join(test_dir, 'btet_1915.cif'))
        structure = parser.get_structures(False)[0]
        s = SpacegroupAnalyzer(structure, symprec=1e-2)
        prim = s.get_primitive_standard_structure()
        self.assertAlmostEqual(prim.lattice.alpha, 105.015053349)
        self.assertAlmostEqual(prim.lattice.beta, 105.015053349)
        self.assertAlmostEqual(prim.lattice.gamma, 118.80658411899999)
        self.assertAlmostEqual(prim.lattice.a, 4.1579321075608791)
        self.assertAlmostEqual(prim.lattice.b, 4.1579321075608791)
        self.assertAlmostEqual(prim.lattice.c, 4.1579321075608791)

        parser = CifParser(os.path.join(test_dir, 'orci_1010.cif'))
        structure = parser.get_structures(False)[0]
        s = SpacegroupAnalyzer(structure, symprec=1e-2)
        prim = s.get_primitive_standard_structure()
        self.assertAlmostEqual(prim.lattice.alpha, 134.78923546600001)
        self.assertAlmostEqual(prim.lattice.beta, 105.856239333)
        self.assertAlmostEqual(prim.lattice.gamma, 91.276341676000001)
        self.assertAlmostEqual(prim.lattice.a, 3.8428217771014852)
        self.assertAlmostEqual(prim.lattice.b, 3.8428217771014852)
        self.assertAlmostEqual(prim.lattice.c, 3.8428217771014852)

        parser = CifParser(os.path.join(test_dir, 'orcc_1003.cif'))
        structure = parser.get_structures(False)[0]
        s = SpacegroupAnalyzer(structure, symprec=1e-2)
        prim = s.get_primitive_standard_structure()
        self.assertAlmostEqual(prim.lattice.alpha, 90)
        self.assertAlmostEqual(prim.lattice.beta, 90)
        self.assertAlmostEqual(prim.lattice.gamma, 164.985257335)
        self.assertAlmostEqual(prim.lattice.a, 15.854897098324196)
        self.assertAlmostEqual(prim.lattice.b, 15.854897098324196)
        self.assertAlmostEqual(prim.lattice.c, 3.99648651)

        parser = CifParser(os.path.join(test_dir, 'monoc_1028.cif'))
        structure = parser.get_structures(False)[0]
        s = SpacegroupAnalyzer(structure, symprec=1e-2)
        prim = s.get_primitive_standard_structure()
        self.assertAlmostEqual(prim.lattice.alpha, 63.579155761999999)
        self.assertAlmostEqual(prim.lattice.beta, 116.42084423747779)
        self.assertAlmostEqual(prim.lattice.gamma, 148.47965136208569)
        self.assertAlmostEqual(prim.lattice.a, 7.2908007159612325)
        self.assertAlmostEqual(prim.lattice.b, 7.2908007159612325)
        self.assertAlmostEqual(prim.lattice.c, 6.8743926325200002)

        parser = CifParser(os.path.join(test_dir, 'rhomb_1170.cif'))
        structure = parser.get_structures(False)[0]
        s = SpacegroupAnalyzer(structure, symprec=1e-2)
        prim = s.get_primitive_standard_structure()
        self.assertAlmostEqual(prim.lattice.alpha, 90)
        self.assertAlmostEqual(prim.lattice.beta, 90)
        self.assertAlmostEqual(prim.lattice.gamma, 120)
        self.assertAlmostEqual(prim.lattice.a, 3.699919902005897)
        self.assertAlmostEqual(prim.lattice.b, 3.699919902005897)
        self.assertAlmostEqual(prim.lattice.c, 6.9779585500000003)
Ejemplo n.º 52
0
    def test_get_conventional_standard_structure(self):
        parser = CifParser(os.path.join(test_dir, 'bcc_1927.cif'))
        structure = parser.get_structures(False)[0]
        s = SpacegroupAnalyzer(structure, symprec=1e-2)
        conv = s.get_conventional_standard_structure()
        self.assertAlmostEqual(conv.lattice.alpha, 90)
        self.assertAlmostEqual(conv.lattice.beta, 90)
        self.assertAlmostEqual(conv.lattice.gamma, 90)
        self.assertAlmostEqual(conv.lattice.a, 9.1980270633769461)
        self.assertAlmostEqual(conv.lattice.b, 9.1980270633769461)
        self.assertAlmostEqual(conv.lattice.c, 9.1980270633769461)

        parser = CifParser(os.path.join(test_dir, 'btet_1915.cif'))
        structure = parser.get_structures(False)[0]
        s = SpacegroupAnalyzer(structure, symprec=1e-2)
        conv = s.get_conventional_standard_structure()
        self.assertAlmostEqual(conv.lattice.alpha, 90)
        self.assertAlmostEqual(conv.lattice.beta, 90)
        self.assertAlmostEqual(conv.lattice.gamma, 90)
        self.assertAlmostEqual(conv.lattice.a, 5.0615106678044235)
        self.assertAlmostEqual(conv.lattice.b, 5.0615106678044235)
        self.assertAlmostEqual(conv.lattice.c, 4.2327080177761687)

        parser = CifParser(os.path.join(test_dir, 'orci_1010.cif'))
        structure = parser.get_structures(False)[0]
        s = SpacegroupAnalyzer(structure, symprec=1e-2)
        conv = s.get_conventional_standard_structure()
        self.assertAlmostEqual(conv.lattice.alpha, 90)
        self.assertAlmostEqual(conv.lattice.beta, 90)
        self.assertAlmostEqual(conv.lattice.gamma, 90)
        self.assertAlmostEqual(conv.lattice.a, 2.9542233922299999)
        self.assertAlmostEqual(conv.lattice.b, 4.6330325651443296)
        self.assertAlmostEqual(conv.lattice.c, 5.373703587040775)

        parser = CifParser(os.path.join(test_dir, 'orcc_1003.cif'))
        structure = parser.get_structures(False)[0]
        s = SpacegroupAnalyzer(structure, symprec=1e-2)
        conv = s.get_conventional_standard_structure()
        self.assertAlmostEqual(conv.lattice.alpha, 90)
        self.assertAlmostEqual(conv.lattice.beta, 90)
        self.assertAlmostEqual(conv.lattice.gamma, 90)
        self.assertAlmostEqual(conv.lattice.a, 4.1430033493799998)
        self.assertAlmostEqual(conv.lattice.b, 31.437979757624728)
        self.assertAlmostEqual(conv.lattice.c, 3.99648651)

        parser = CifParser(os.path.join(test_dir, 'monoc_1028.cif'))
        structure = parser.get_structures(False)[0]
        s = SpacegroupAnalyzer(structure, symprec=1e-2)
        conv = s.get_conventional_standard_structure()
        self.assertAlmostEqual(conv.lattice.alpha, 90)
        self.assertAlmostEqual(conv.lattice.beta, 117.53832420192903)
        self.assertAlmostEqual(conv.lattice.gamma, 90)
        self.assertAlmostEqual(conv.lattice.a, 14.033435583000625)
        self.assertAlmostEqual(conv.lattice.b, 3.96052850731)
        self.assertAlmostEqual(conv.lattice.c, 6.8743926325200002)

        parser = CifParser(os.path.join(test_dir, 'rhomb_1170.cif'))
        structure = parser.get_structures(False)[0]
        s = SpacegroupAnalyzer(structure, symprec=1e-2)
        conv = s.get_conventional_standard_structure()
        self.assertAlmostEqual(conv.lattice.alpha, 90)
        self.assertAlmostEqual(conv.lattice.beta, 90)
        self.assertAlmostEqual(conv.lattice.gamma, 120)
        self.assertAlmostEqual(conv.lattice.a, 3.699919902005897)
        self.assertAlmostEqual(conv.lattice.b, 3.699919902005897)
        self.assertAlmostEqual(conv.lattice.c, 6.9779585500000003)
Ejemplo n.º 53
0
import argparse, plotter
from pymatgen.io.cifio import CifParser
out_file = '/Users/dejacor/Documents/screening'
parser = argparse.ArgumentParser(
    description='convert zeolite unit cell from cif to xyz format')
parser.add_argument('-c', '--cifFile', help='zeolite pdb file name')
args = parser.parse_args()
cif_file = args.cifFile
cif = CifParser(cif_file)
struc = cif.get_structures(primitive=False)[0]

DATA = {}
for atom in range(len(struc)):
    xyz = struc[atom].as_dict()['xyz']
    element = struc[atom].as_dict()['label']
    if not element in DATA.keys():
        DATA[element] = [xyz]
    else:
        DATA[element].append(xyz)

# gotta correct data, for some reason they pull in my Si's as S's
corData = {}
for element in DATA.keys():
    if element == 'S':
        corData['Si'] = DATA['S']
    else:
        corData[element] = DATA[element]
name_of_zeo = list(cif.as_dict().keys())[0]
xyz_file = cif_file[:cif_file.rfind('/')] + '/%s.xyz' % name_of_zeo
plotter.xyz(xyz_file, corData)
Ejemplo n.º 54
0
from __future__ import unicode_literals

import unittest
import os

from pymatgen.io.feffio_set import FeffInputSet
from pymatgen.io.feffio import FeffPot
from pymatgen.io.cifio import CifParser

test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..",
                        'test_files')
cif_file = 'CoO19128.cif'
central_atom = 'O'
cif_path = os.path.join(test_dir, cif_file)
r = CifParser(cif_path)
structure = r.get_structures()[0]
x = FeffInputSet("MaterialsProject")


class FeffInputSetTest(unittest.TestCase):

    header_string = """* This FEFF.inp file generated by pymatgen
TITLE comment: From cif file
TITLE Source:  CoO19128.cif
TITLE Structure Summary:  Co2 O2
TITLE Reduced formula:  CoO
TITLE space group: (P6_3mc), space number:  (186)
TITLE abc:  3.297078   3.297078   5.254213
TITLE angles: 90.000000  90.000000 120.000000
TITLE sites: 4
* 1 Co     0.333334     0.666666     0.503676
Ejemplo n.º 55
0
    def test_get_conventional_standard_structure(self):
        parser = CifParser(os.path.join(test_dir, 'bcc_1927.cif'))
        structure = parser.get_structures(False)[0]
        s = SymmetryFinder(structure, symprec=1e-2)
        conv = s.get_conventional_standard_structure()
        self.assertAlmostEqual(conv.lattice.alpha, 90)
        self.assertAlmostEqual(conv.lattice.beta, 90)
        self.assertAlmostEqual(conv.lattice.gamma, 90)
        self.assertAlmostEqual(conv.lattice.a, 9.1980270633769461)
        self.assertAlmostEqual(conv.lattice.b, 9.1980270633769461)
        self.assertAlmostEqual(conv.lattice.c, 9.1980270633769461)

        parser = CifParser(os.path.join(test_dir, 'btet_1915.cif'))
        structure = parser.get_structures(False)[0]
        s = SymmetryFinder(structure, symprec=1e-2)
        conv = s.get_conventional_standard_structure()
        self.assertAlmostEqual(conv.lattice.alpha, 90)
        self.assertAlmostEqual(conv.lattice.beta, 90)
        self.assertAlmostEqual(conv.lattice.gamma, 90)
        self.assertAlmostEqual(conv.lattice.a, 5.0615106678044235)
        self.assertAlmostEqual(conv.lattice.b, 5.0615106678044235)
        self.assertAlmostEqual(conv.lattice.c, 4.2327080177761687)

        parser = CifParser(os.path.join(test_dir, 'orci_1010.cif'))
        structure = parser.get_structures(False)[0]
        s = SymmetryFinder(structure, symprec=1e-2)
        conv = s.get_conventional_standard_structure()
        self.assertAlmostEqual(conv.lattice.alpha, 90)
        self.assertAlmostEqual(conv.lattice.beta, 90)
        self.assertAlmostEqual(conv.lattice.gamma, 90)
        self.assertAlmostEqual(conv.lattice.a, 2.9542233922299999)
        self.assertAlmostEqual(conv.lattice.b, 4.6330325651443296)
        self.assertAlmostEqual(conv.lattice.c, 5.373703587040775)

        parser = CifParser(os.path.join(test_dir, 'orcc_1003.cif'))
        structure = parser.get_structures(False)[0]
        s = SymmetryFinder(structure, symprec=1e-2)
        conv = s.get_conventional_standard_structure()
        self.assertAlmostEqual(conv.lattice.alpha, 90)
        self.assertAlmostEqual(conv.lattice.beta, 90)
        self.assertAlmostEqual(conv.lattice.gamma, 90)
        self.assertAlmostEqual(conv.lattice.a, 4.1430033493799998)
        self.assertAlmostEqual(conv.lattice.b, 31.437979757624728)
        self.assertAlmostEqual(conv.lattice.c, 3.99648651)

        parser = CifParser(os.path.join(test_dir, 'monoc_1028.cif'))
        structure = parser.get_structures(False)[0]
        s = SymmetryFinder(structure, symprec=1e-2)
        conv = s.get_conventional_standard_structure()
        self.assertAlmostEqual(conv.lattice.alpha, 90)
        self.assertAlmostEqual(conv.lattice.beta, 117.53832420192903)
        self.assertAlmostEqual(conv.lattice.gamma, 90)
        self.assertAlmostEqual(conv.lattice.a, 14.033435583000625)
        self.assertAlmostEqual(conv.lattice.b, 3.96052850731)
        self.assertAlmostEqual(conv.lattice.c, 6.8743926325200002)

        parser = CifParser(os.path.join(test_dir, 'rhomb_1170.cif'))
        structure = parser.get_structures(False)[0]
        s = SymmetryFinder(structure, symprec=1e-2)
        conv = s.get_conventional_standard_structure()
        self.assertAlmostEqual(conv.lattice.alpha, 90)
        self.assertAlmostEqual(conv.lattice.beta, 90)
        self.assertAlmostEqual(conv.lattice.gamma, 120)
        self.assertAlmostEqual(conv.lattice.a, 3.699919902005897)
        self.assertAlmostEqual(conv.lattice.b, 3.699919902005897)
        self.assertAlmostEqual(conv.lattice.c, 6.9779585500000003)
Ejemplo n.º 56
0
    def test_get_primitive_standard_structure(self):
        parser = CifParser(os.path.join(test_dir, 'bcc_1927.cif'))
        structure = parser.get_structures(False)[0]
        s = SymmetryFinder(structure, symprec=1e-2)
        prim = s.get_primitive_standard_structure()
        self.assertAlmostEqual(prim.lattice.alpha, 109.47122063400001)
        self.assertAlmostEqual(prim.lattice.beta, 109.47122063400001)
        self.assertAlmostEqual(prim.lattice.gamma, 109.47122063400001)
        self.assertAlmostEqual(prim.lattice.a, 7.9657251015812145)
        self.assertAlmostEqual(prim.lattice.b, 7.9657251015812145)
        self.assertAlmostEqual(prim.lattice.c, 7.9657251015812145)

        parser = CifParser(os.path.join(test_dir, 'btet_1915.cif'))
        structure = parser.get_structures(False)[0]
        s = SymmetryFinder(structure, symprec=1e-2)
        prim = s.get_primitive_standard_structure()
        self.assertAlmostEqual(prim.lattice.alpha, 105.015053349)
        self.assertAlmostEqual(prim.lattice.beta, 105.015053349)
        self.assertAlmostEqual(prim.lattice.gamma, 118.80658411899999)
        self.assertAlmostEqual(prim.lattice.a, 4.1579321075608791)
        self.assertAlmostEqual(prim.lattice.b, 4.1579321075608791)
        self.assertAlmostEqual(prim.lattice.c, 4.1579321075608791)

        parser = CifParser(os.path.join(test_dir, 'orci_1010.cif'))
        structure = parser.get_structures(False)[0]
        s = SymmetryFinder(structure, symprec=1e-2)
        prim = s.get_primitive_standard_structure()
        self.assertAlmostEqual(prim.lattice.alpha, 134.78923546600001)
        self.assertAlmostEqual(prim.lattice.beta, 105.856239333)
        self.assertAlmostEqual(prim.lattice.gamma, 91.276341676000001)
        self.assertAlmostEqual(prim.lattice.a, 3.8428217771014852)
        self.assertAlmostEqual(prim.lattice.b, 3.8428217771014852)
        self.assertAlmostEqual(prim.lattice.c, 3.8428217771014852)

        parser = CifParser(os.path.join(test_dir, 'orcc_1003.cif'))
        structure = parser.get_structures(False)[0]
        s = SymmetryFinder(structure, symprec=1e-2)
        prim = s.get_primitive_standard_structure()
        self.assertAlmostEqual(prim.lattice.alpha, 90)
        self.assertAlmostEqual(prim.lattice.beta, 90)
        self.assertAlmostEqual(prim.lattice.gamma, 164.985257335)
        self.assertAlmostEqual(prim.lattice.a, 15.854897098324196)
        self.assertAlmostEqual(prim.lattice.b, 15.854897098324196)
        self.assertAlmostEqual(prim.lattice.c, 3.99648651)

        parser = CifParser(os.path.join(test_dir, 'monoc_1028.cif'))
        structure = parser.get_structures(False)[0]
        s = SymmetryFinder(structure, symprec=1e-2)
        prim = s.get_primitive_standard_structure()
        self.assertAlmostEqual(prim.lattice.alpha, 63.579155761999999)
        self.assertAlmostEqual(prim.lattice.beta, 116.42084423747779)
        self.assertAlmostEqual(prim.lattice.gamma, 148.47965136208569)
        self.assertAlmostEqual(prim.lattice.a, 7.2908007159612325)
        self.assertAlmostEqual(prim.lattice.b, 7.2908007159612325)
        self.assertAlmostEqual(prim.lattice.c, 6.8743926325200002)

        parser = CifParser(os.path.join(test_dir, 'rhomb_1170.cif'))
        structure = parser.get_structures(False)[0]
        s = SymmetryFinder(structure, symprec=1e-2)
        prim = s.get_primitive_standard_structure()
        self.assertAlmostEqual(prim.lattice.alpha, 90)
        self.assertAlmostEqual(prim.lattice.beta, 90)
        self.assertAlmostEqual(prim.lattice.gamma, 120)
        self.assertAlmostEqual(prim.lattice.a, 3.699919902005897)
        self.assertAlmostEqual(prim.lattice.b, 3.699919902005897)
        self.assertAlmostEqual(prim.lattice.c, 6.9779585500000003)