Exemple #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)
    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")
Exemple #4
0
 def set_structure_from_inputs(self, input_options):
     """Make a pymatgen structure and update the
         structure key.
         Args:
             input_options <InputOptions>
     """
     strposfile = input_options.get_item('structure', 'posfile')
     if strposfile is None:
         iopscoords = input_options.get_item('structure', 'coordinates')
         iopslatt = input_options.get_item('structure', 'lattice')
         iopsatoms = input_options.get_item('structure', 'atom_list')
         iopsctype = input_options.get_item('structure', 'coord_type')
         structure = MAST2Structure(lattice=iopslatt,
                                    coordinates=iopscoords,
                                    atom_list=iopsatoms,
                                    coord_type=iopsctype)
     elif ('poscar' in strposfile.lower()):
         from pymatgen.io.vaspio import Poscar
         structure = Poscar.from_file(strposfile).structure
     elif ('cif' in strposfile.lower()):
         from pymatgen.io.cifio import CifParser
         structure = CifParser(strposfile).get_structures()[0]
     else:
         error = 'Cannot build structure from file %s' % strposfile
         raise MASTError(self.__class__.__name__, error)
     input_options.update_item('structure', 'structure', structure)
     if input_options.get_item('structure', 'use_structure_index') in [
             'True', 'true', 'T', 't'
     ]:
         self.do_structure_indexing(input_options)
     return
Exemple #5
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)
Exemple #6
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!")
Exemple #7
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)
Exemple #8
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)
Exemple #9
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)
Exemple #10
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))
Exemple #11
0
 def setUp(self):
     filepath1 = os.path.join(test_dir, 'Li2O.cif')
     p = CifParser(filepath1).get_structures(False)[0]
     bv = BVAnalyzer()
     valences = bv.get_valences(p)
     el = [site.species_string for site in p.sites]
     val_dict = dict(zip(el, valences))
     self._radii = {}
     for k, v in val_dict.items():
         k1 = re.sub('[1-9,+,\-]', '', k)
         self._radii[k] = Specie(k1, v).ionic_radius
     p.remove(0)
     self._vac_struct = p
Exemple #12
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)
Exemple #13
0
def inter_energy_gen(cif_file):
    # Use the number as struct identifier
    # Store the remaining string as formula
    dir, filen = os.path.split(cif_file)
    name = os.path.splitext(filen)[0]
    item = name.split('--')
    #key = item[0]
    inter_descript_dict = {'formula':''.join(item[1].split())}

    #read the file to pymatgen struct
    try:
        struct = CifParser(cif_file).get_structures(False)[0]
    except:
        print 'reading ', cif_file, ' failed'
        return None, filen


    try:
        struct_val_rad = StructWithValenceIonicRadius(struct)
    except:
        print inter_descript_dict['formula']
        print "Unable to identify radii and valences"
        return None, filen

    inter = Interstitial(struct_val_rad)
    #inter.prune_defectsites('Mn', 3)
    no_inter = inter.defectsite_count()
    print "No of interstitials: ", no_inter
    #inter.reduce_defectsites()
    #no_inter = inter.defectsite_count()
    #print "No of interstitials: ", no_inter
    ife = InterstitialFormationEnergy(inter)
    inter_descript_dict['no_inter'] = no_inter

    #Create a list storing a dictionary of properties for each interstitial
    inter_list = []
    for i in range(no_inter):
        inter_dict = {}
        inter_dict['radius'] = inter.get_radius(i)
        #try:
        #    inter_dict['energy'] = ife.get_energy_fixsc(i, 'Mn', 3, relax=False)
        inter_dict['energy'] = ife.get_energy_fixsc(i, 'Mn', 3, relax=True)
        #except:
        #    inter_dict['energy'] = 'NaN'
        print i, inter_dict['radius'], inter_dict['energy']
        inter_list.append(inter_dict)
    inter_descript_dict['interstitials'] = inter_list
    inter_descript_dict
Exemple #14
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)
Exemple #15
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")
Exemple #16
0
 def get_coordinates_only_structure_from_input(self):
     """Get coordinates-only structures from mast_coordinates
         ingredient keyword
         Args:
             keywords <dict>: ingredient keywords
         Returns:
             coordstrucs <list>: list of Structure objects
     """
     coordposlist = self.keywords['program_keys']['mast_coordinates']
     coordstrucs = list()
     coordstruc = None
     for coordpositem in coordposlist:
         if ('poscar' in os.path.basename(coordpositem).lower()):
             coordstruc = Poscar.from_file(coordpositem).structure
         elif ('cif' in os.path.basename(coordpositem).lower()):
             coordstruc = CifParser(coordpositem).get_structures()[0]
         else:
             error = 'Cannot build structure from file %s' % coordpositem
             raise MASTError(self.__class__.__name__, error)
         coordstrucs.append(coordstruc)
     return coordstrucs
Exemple #17
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
Exemple #18
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)
Exemple #19
0
        filelist.remove(filen)

# Use the number as struct identifier
# Store the remaining string as formula
struct_descript_dict = {}
for filen in filelist[0:20]:
    name = os.path.splitext(filen)[0]
    item = name.split('--')
    key = item[0]
    struct_descript_dict[key] = {'formula': ''.join(item[1].split())}
    #print item

    #read the file to pymatgen struct
    filename = os.path.join(struct_dir, filen)
    try:
        struct = CifParser(filename).get_structures()[0]
    except:
        print filename
        del struct_descript_dict[key]
        continue
    try:
        vac = Vacancy(struct)
    except:
        print struct_descript_dict[key]['formula']
        del struct_descript_dict[key]
        continue
    no_vac = vac.defectsite_count()
    #print no_vac
    # add number of vacancies to descriptor
    struct_descript_dict[key]['no_vac'] = no_vac
Exemple #20
0
        filelist.remove(filen)

# Use the number as struct identifier
# Store the remaining string as formula
struct_descript_dict = {}
for filen in filelist[0:10]:
    name = os.path.splitext(filen)[0]
    item = name.split('--')
    key = item[0]
    struct_descript_dict[key] = {'formula':''.join(item[1].split())}
    print name

    #read the file to pymatgen struct
    filename = os.path.join(struct_dir,filen)
    try:
        struct = CifParser(filename).get_structures(primitive=False)[0]
    except:
        print 'reading ', filename, ' failed'
        del struct_descript_dict[key]
        print struct_descript_dict.keys()
        continue

    import sys
    #print >>sys.stderr, struct
    try:
        inter = Interstitial(struct)
    except:
        print 'interstitial not generated for ', struct_descript_dict[key]['formula']
        del struct_descript_dict[key]
        continue
Exemple #21
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)
Exemple #22
0
    fws = []
    connections = {}

    # add the root FW (GGA+U)
    spec = _snl_to_spec(snl, enforce_gga=False)
    tasks = [VaspWriterTask(), get_custodian_task(spec)]
    fws.append(Firework(tasks, spec, fw_id=1))

    # add GGA insertion to DB
    spec = {'task_type': 'VASP db insertion', '_priority': 2,
            '_category': 'VASP', '_queueadapter': QA_VASP}
    fws.append(Firework([VaspToDBTask()], spec, fw_id=2))
    connections[1] = 2
    mpvis = MPVaspInputSet()

    spec['vaspinputset_name'] = mpvis.__class__.__name__

    return Workflow(fws, connections, name=Composition(snl.structure.composition.reduced_formula).alphabetical_formula)
"""

if __name__ == '__main__':
    s1 = CifParser('test_wfs/Si.cif').get_structures()[0]
    s2 = CifParser('test_wfs/FeO.cif').get_structures()[0]

    snl1 = StructureNL(s1, "Anubhav Jain <*****@*****.**>")
    snl2 = StructureNL(s2, "Anubhav Jain <*****@*****.**>")

    snl_to_wf(snl1).to_file('test_wfs/wf_si_dupes.json', indent=4)
    snl_to_wf(snl2).to_file('test_wfs/wf_feo_dupes.json', indent=4)
Exemple #23
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")
 def setUp(self):
     filepath = os.path.join(test_dir, 'LiFePO4.cif')
     parser = CifParser(filepath)
     self.s = parser.get_structures()[0]
                    metavar='central_atom',
                    type=str,
                    nargs=1,
                    help='symbol of absorbing atom')
parser.add_argument('calc_type',
                    metavar='calc_type',
                    type=str,
                    nargs=1,
                    help='type of calc, currently XANES or EXAFS')

args = parser.parse_args()
cif_file = args.cif_file[0]
central_atom = args.central_atom[0]
calc_type = args.calc_type[0]

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

source = os.path.basename(cif_file)
comment = 'From cif file'

header = FeffInputSet.get_header(x, structure, source, comment)
print "\n\nHEADER\n"
print header

tags = FeffInputSet.get_feff_tags(x, calc_type)
print "\n\nPARAMETERS\n"
print tags

POT = FeffInputSet.get_feff_pot(x, structure, central_atom)
Exemple #26
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)
Exemple #27
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
Exemple #28
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)
 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")])
            pass
        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)