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")
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!")
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!")
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!")
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_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")
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)
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)
def convert_fmt(args): iformat = args.input_format[0] oformat = args.output_format[0] filename = args.input_filename[0] out_filename = args.output_filename[0] try: if iformat == "smart": structure = read_structure(filename) if iformat == "POSCAR": p = Poscar.from_file(filename) structure = p.structure elif iformat == "CIF": r = CifParser(filename) structure = r.get_structures()[0] elif iformat == "CSSR": structure = Cssr.from_file(filename).structure if oformat == "smart": write_structure(structure, out_filename) elif oformat == "POSCAR": p = Poscar(structure) p.write_file(out_filename) elif oformat == "CIF": w = CifWriter(structure) w.write_file(out_filename) elif oformat == "CSSR": c = Cssr(structure) c.write_file(out_filename) elif oformat == "VASP": input_set = MPVaspInputSet() ts = TransformedStructure(structure, [], history=[{ "source": "file", "datetime": str(datetime.datetime.now()), "original_file": open(filename).read() }]) ts.write_vasp_input(input_set, output_dir=out_filename) elif oformat == "MITVASP": input_set = MITVaspInputSet() ts = TransformedStructure(structure, [], history=[{ "source": "file", "datetime": str(datetime.datetime.now()), "original_file": open(filename).read() }]) ts.write_vasp_input(input_set, output_dir=out_filename) except Exception as ex: print "Error converting file. Are they in the right format?" print str(ex)
def test_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.")
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"})
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)
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)
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))
def convert_fmt(args): iformat = args.input_format[0] oformat = args.output_format[0] filename = args.input_filename[0] out_filename = args.output_filename[0] try: if iformat == "smart": structure = read_structure(filename) if iformat == "POSCAR": p = Poscar.from_file(filename) structure = p.structure elif iformat == "CIF": r = CifParser(filename) structure = r.get_structures()[0] elif iformat == "CSSR": structure = Cssr.from_file(filename).structure if oformat == "smart": write_structure(structure, out_filename) elif oformat == "POSCAR": p = Poscar(structure) p.write_file(out_filename) elif oformat == "CIF": w = CifWriter(structure) w.write_file(out_filename) elif oformat == "CSSR": c = Cssr(structure) c.write_file(out_filename) elif oformat == "VASP": input_set = MPVaspInputSet() ts = TransformedStructure( structure, [], history=[ {"source": "file", "datetime": str(datetime.datetime.now()), "original_file": open(filename).read()} ], ) ts.write_vasp_input(input_set, output_dir=out_filename) elif oformat == "MITVASP": input_set = MITVaspInputSet() ts = TransformedStructure( structure, [], history=[ {"source": "file", "datetime": str(datetime.datetime.now()), "original_file": open(filename).read()} ], ) ts.write_vasp_input(input_set, output_dir=out_filename) except Exception as ex: print "Error converting file. Are they in the right format?" print str(ex)
def test_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 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
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
def setUp(self): p = Poscar.from_file(os.path.join(test_dir, 'POSCAR')) self.structure = p.struct 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.struct editor = StructureEditor(p.struct) 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)
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)
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)
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)
def from_cif_string(cif_string, transformations=[], primitive=True): """ Generates TransformedStructure from a cif string. Args: cif_string: Input cif string. Should contain only one structure. For cifs containing multiple structures, please use CifTransmuter. transformations: Sequence of transformations to be applied to the input structure. primitive: Option to set if the primitive cell should be extracted. Defaults to True. However, there are certain instances where you might want to use a non-primitive cell, e.g., if you are trying to generate all possible orderings of partial removals or order a disordered structure. """ parser = CifParser.from_string(cif_string) raw_string = re.sub("'", "\"", cif_string) cif_dict = parser.to_dict cif_keys = cif_dict.keys() s = parser.get_structures(primitive)[0] partial_cif = cif_dict[cif_keys[0]] if '_database_code_ICSD' in partial_cif: source = partial_cif['_database_code_ICSD'] + "-ICSD" else: source = 'uploaded cif' source_info = {'source':source, 'datetime':str(datetime.datetime.now()), 'original_file':raw_string, 'cif_data':cif_dict[cif_keys[0]]} return TransformedStructure(s, transformations, [source_info])
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)
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
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
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)
def test_get_lattice_from_lattice_type(self): cif_structure = """#generated using pymatgen data_FePO4 _symmetry_space_group_name_H-M Pnma _cell_length_a 10.41176687 _cell_length_b 6.06717188 _cell_length_c 4.75948954 _chemical_formula_structural FePO4 _chemical_formula_sum 'Fe4 P4 O16' _cell_volume 300.65685512 _cell_formula_units_Z 4 _symmetry_cell_setting Orthorhombic 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_occupancy Fe Fe1 1 0.218728 0.750000 0.474867 1 Fe Fe2 1 0.281272 0.250000 0.974867 1 Fe Fe3 1 0.718728 0.750000 0.025133 1 Fe Fe4 1 0.781272 0.250000 0.525133 1 P P5 1 0.094613 0.250000 0.418243 1 P P6 1 0.405387 0.750000 0.918243 1 P P7 1 0.594613 0.250000 0.081757 1 P P8 1 0.905387 0.750000 0.581757 1 O O9 1 0.043372 0.750000 0.707138 1 O O10 1 0.096642 0.250000 0.741320 1 O O11 1 0.165710 0.046072 0.285384 1 O O12 1 0.165710 0.453928 0.285384 1 O O13 1 0.334290 0.546072 0.785384 1 O O14 1 0.334290 0.953928 0.785384 1 O O15 1 0.403358 0.750000 0.241320 1 O O16 1 0.456628 0.250000 0.207138 1 O O17 1 0.543372 0.750000 0.792862 1 O O18 1 0.596642 0.250000 0.758680 1 O O19 1 0.665710 0.046072 0.214616 1 O O20 1 0.665710 0.453928 0.214616 1 O O21 1 0.834290 0.546072 0.714616 1 O O22 1 0.834290 0.953928 0.714616 1 O O23 1 0.903358 0.750000 0.258680 1 O O24 1 0.956628 0.250000 0.292862 1 """ cp = CifParser.from_string(cif_structure) s_test = cp.get_structures(False)[0] filepath = os.path.join(test_dir, 'POSCAR') poscar = Poscar.from_file(filepath) s_ref = poscar.structure sm = StructureMatcher(stol=0.05, ltol=0.01, angle_tol=0.1) self.assertTrue(sm.fit(s_ref, s_test))
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")
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
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
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!")
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)
def convert_fmt(args): iformat = args.input_format[0] oformat = args.output_format[0] filename = args.input_filename[0] out_filename = args.output_filename[0] try: if iformat == "smart": structure = read_structure(filename) if iformat == "POSCAR": p = Poscar.from_file(filename) structure = p.structure elif iformat == "CIF": r = CifParser(filename) structure = r.get_structures()[0] elif iformat == "CSSR": structure = Cssr.from_file(filename).structure if oformat == "smart": write_structure(structure, out_filename) elif oformat == "POSCAR": p = Poscar(structure) p.write_file(out_filename) elif oformat == "CIF": w = CifWriter(structure) w.write_file(out_filename) elif oformat == "CSSR": c = Cssr(structure) c.write_file(out_filename) elif oformat == "VASP": input_set = MaterialsProjectVaspInputSet() transmuter = StandardTransmuter.from_structures([structure], []) transmuter.write_vasp_input(input_set, output_dir=out_filename) except Exception as ex: print "Error converting file. Are they in the right format?" print str(ex)
def 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)
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)
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
def from_cif_string(cif_string, transformations=None, primitive=True, occupancy_tolerance=1.): """ Generates TransformedStructure from a cif string. Args: cif_string (str): Input cif string. Should contain only one structure. For cifs containing multiple structures, please use CifTransmuter. transformations ([Transformations]): Sequence of transformations to be applied to the input structure. primitive (bool): Option to set if the primitive cell should be extracted. Defaults to True. However, there are certain instances where you might want to use a non-primitive cell, e.g., if you are trying to generate all possible orderings of partial removals or order a disordered structure. occupancy_tolerance (float): If total occupancy of a site is between 1 and occupancy_tolerance, the occupancies will be scaled down to 1. Returns: TransformedStructure """ parser = CifParser.from_string(cif_string, occupancy_tolerance) raw_string = re.sub("'", "\"", cif_string) cif_dict = parser.to_dict cif_keys = cif_dict.keys() s = parser.get_structures(primitive)[0] partial_cif = cif_dict[cif_keys[0]] if "_database_code_ICSD" in partial_cif: source = partial_cif["_database_code_ICSD"] + "-ICSD" else: source = "uploaded cif" source_info = { "source": source, "datetime": str(datetime.datetime.now()), "original_file": raw_string, "cif_data": cif_dict[cif_keys[0]] } return TransformedStructure(s, transformations, history=[source_info])
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
def from_cif_string(cif_string, transformations=None, primitive=True, occupancy_tolerance=1.): """ Generates TransformedStructure from a cif string. Args: cif_string (str): Input cif string. Should contain only one structure. For cifs containing multiple structures, please use CifTransmuter. transformations ([Transformations]): Sequence of transformations to be applied to the input structure. primitive (bool): Option to set if the primitive cell should be extracted. Defaults to True. However, there are certain instances where you might want to use a non-primitive cell, e.g., if you are trying to generate all possible orderings of partial removals or order a disordered structure. occupancy_tolerance (float): If total occupancy of a site is between 1 and occupancy_tolerance, the occupancies will be scaled down to 1. Returns: TransformedStructure """ parser = CifParser.from_string(cif_string, occupancy_tolerance) raw_string = re.sub("'", "\"", cif_string) cif_dict = parser.to_dict cif_keys = cif_dict.keys() s = parser.get_structures(primitive)[0] partial_cif = cif_dict[cif_keys[0]] if "_database_code_ICSD" in partial_cif: source = partial_cif["_database_code_ICSD"] + "-ICSD" else: source = "uploaded cif" source_info = {"source": source, "datetime": str(datetime.datetime.now()), "original_file": raw_string, "cif_data": cif_dict[cif_keys[0]]} return TransformedStructure(s, transformations, history=[source_info])
def test_no_coords_or_species(self): string= """#generated using pymatgen data_Si1.5N1.5 _symmetry_space_group_name_H-M 'P 1' _cell_length_a 3.84019793 _cell_length_b 3.84019899 _cell_length_c 3.84019793 _cell_angle_alpha 119.99999086 _cell_angle_beta 90.00000000 _cell_angle_gamma 60.00000914 _symmetry_Int_Tables_number 1 _chemical_formula_structural Si1.5N1.5 _chemical_formula_sum 'Si1.5 N1.5' _cell_volume 40.0447946443 _cell_formula_units_Z 0 loop_ _symmetry_equiv_pos_site_id _symmetry_equiv_pos_as_xyz 1 'x, y, z' loop_ _atom_type_symbol _atom_type_oxidation_number Si3+ 3.0 Si4+ 4.0 N3- -3.0 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_occupancy ? ? ? ? ? ? ? """ parser = CifParser.from_string(string) self.assertEqual(len(parser.get_structures()), 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 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)
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
def setUp(self): filepath = os.path.join(test_dir, 'LiFePO4.cif') parser = CifParser(filepath) self.s = parser.get_structures()[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)
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)
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)
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)
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
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)
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")])
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