def _vasp_poscar_setup(self): """Set up the POSCAR file for a single VASP run. """ name = self.keywords['name'] pospath = os.path.join(name, "POSCAR") if os.path.isfile(pospath): my_poscar = Poscar.from_file(pospath) #parent should have given a structure else: #this is an originating run; mast should give it a structure if self.keywords['structure'] is not None: my_poscar = Poscar(self.keywords['structure']) else: pf = os.path.join(os.path.dirname(name),'POSCAR_%s'%os.path.basename(name)) if os.path.isfile(pf): my_poscar = Poscar.from_file(pf) workdir=os.path.dirname(name) sdir=os.path.join(workdir,"structure_index_files") if os.path.exists(sdir): mystr=my_poscar.structure manname="manifest___" myatomindex=AtomIndex(structure_index_directory=sdir) newstr=myatomindex.graft_new_coordinates_from_manifest(mystr, manname, "") self.logger.info("Getting original coordinates from manifest.") new_pos=Poscar(newstr) my_poscar=new_pos self.logger.info("No POSCAR found from a parent; base structure used for %s" % self.keywords['name']) if 'mast_coordinates' in self.keywords['program_keys'].keys(): sxtend = StructureExtensions(struc_work1=my_poscar.structure, name=self.keywords['name']) coordstrucs=self.get_coordinates_only_structure_from_input() newstruc = sxtend.graft_coordinates_onto_structure(coordstrucs[0]) my_poscar.structure=newstruc.copy() dirutil.lock_directory(name) my_poscar.write_file(pospath) dirutil.unlock_directory(name) return my_poscar
def main(): s1name = "geometry/BCC_to_FCC/POSCAR_BCC" s2name = "geometry/BCC_to_FCC/POSCAR_FCC" s1 = Poscar.from_file(s1name).structure s2 = Poscar.from_file(s2name).structure # print s1,s2 smatcher = StructureMatcher(primitive_cell=False) res = smatcher.get_transformation(s1, s2) print res
def checkrelax_single(path, src_ini="posfinal", src_fin="posfinal3"): dirc = path initial = Poscar.from_file(os.path.join(dirc, src_ini)).structure.as_dict()["lattice"] final = Poscar.from_file(os.path.join(dirc, src_fin)).structure.as_dict()["lattice"] length_a = final[u"a"] / initial[u"a"] length_b = final[u"b"] / initial[u"b"] length_c = final[u"c"] / initial[u"c"] delta_length = ((length_b / length_a - 1) ** 2 + (length_c / length_a - 1) ** 2) ** 0.5 # print(delta_length) angle_a = final["alpha"] / initial["alpha"] - 1 angle_b = final["beta"] / initial["beta"] - 1 angle_c = final["gamma"] / initial["gamma"] - 1 delta_angle = (angle_a ** 2 + angle_b ** 2 + angle_c ** 2) ** 0.5 # print(delta_angle) return delta_length, delta_angle
def five(src="POSCAR"): """ ver5 に変換 """ srcpos = Poscar.from_file(src) dst = "POSCAR_five" srcpos.write_file(dst)
def test_init_from_structure(self): filepath = os.path.join(test_dir, "POSCAR") poscar = Poscar.from_file(filepath) struct = poscar.struct xyz = XYZ(struct) ans = """24 Fe4 P4 O16 Fe 2.277347 4.550379 2.260125 Fe 2.928536 1.516793 4.639870 Fe 7.483231 4.550379 0.119620 Fe 8.134420 1.516793 2.499364 P 0.985089 1.516793 1.990624 P 4.220794 4.550379 4.370369 P 6.190973 1.516793 0.389120 P 9.426677 4.550379 2.768865 O 0.451582 4.550379 3.365614 O 1.006219 1.516793 3.528306 O 1.725331 0.279529 1.358282 O 1.725331 2.754057 1.358282 O 3.480552 3.313115 3.738027 O 3.480552 5.787643 3.738027 O 4.199665 4.550379 1.148562 O 4.754301 1.516793 0.985870 O 5.657466 4.550379 3.773620 O 6.212102 1.516793 3.610928 O 6.931215 0.279529 1.021463 O 6.931215 2.754057 1.021463 O 8.686436 3.313115 3.401208 O 8.686436 5.787643 3.401208 O 9.405548 4.550379 1.231183 O 9.960184 1.516793 1.393875""" self.assertEqual(str(xyz), ans)
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 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 print_spg(src="POSCAR"): srcpos = Poscar.from_file(src) finder = SpacegroupAnalyzer(srcpos.structure, symprec=5e-2, angle_tolerance=8) spg = finder.get_spacegroup_symbol() spg_num = finder.get_spacegroup_number() print(spg) print(spg_num)
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 get_structure_from_file(self, myfilepath=""): """Get the structure from a specified file path. For VASP, this is a POSCAR-type file. Args: myfilepath <str>: File path for structure. """ return Poscar.from_file(myfilepath).structure
def supercell(poscar,scale,outFile=None,replace=False): '''Reads in a structure in VASP POSCAR format and returns one with a supercell of that structure Args: ------------------------------------- poscar: location of POSCAR file to find supercell of scale: iterable of integer scaling factors with length 3. kwargs: ------------------------------------- outFile: location for new poscar file with modifies: ------------------------------------- outFile: if replace=True poscar: if replace=False ''' assert os.path.isfile(poscar) assert replace==True or not outFile is None p = Poscar.from_file(poscar,False) # with open(poscar) as f: # poscomment = f.readline().strip() # # p.comment = poscomment p.structure.make_supercell(scale) if replace==True: p.write_file(poscar,vasp4_compatible=True) else: p.write_file(outFile,vasp4_compatible=True)
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 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 get_elements(src): """ 組成比を得るための method """ srcpos = Poscar.from_file(src) elements = [x.symbol for x in srcpos.structure.species] elem_counter = Counter(elements) return elem_counter
def get_primitive(fname): poscar = Poscar.from_file(fname) finder = SymmetryFinder(poscar.structure) spg_num = finder.get_spacegroup_number() primitive = finder.get_primitive_standard_structure() return spg_num, primitive
def test_to_from_dict(self): json_str = json.dumps(PartialRemoveSpecieTransformation("Li+", 0.5, PartialRemoveSpecieTransformation.ALGO_BEST_FIRST).to_dict) t = transformation_from_json(json_str) module_dir = os.path.dirname(os.path.abspath(__file__)) p = Poscar.from_file(os.path.join(module_dir, 'POSCAR.LiFePO4')) t1 = OxidationStateDecorationTransformation({"Li":1, "Fe":2, "P":5, "O":-2}) s = t1.apply_transformation(p.struct) self.assertEqual(len(t.apply_transformation(s)), 26)
def test_apply_transformations_complete_ranking(self): module_dir = os.path.dirname(os.path.abspath(__file__)) p = Poscar.from_file(os.path.join(module_dir, 'POSCAR.LiFePO4')) t1 = OxidationStateDecorationTransformation({"Li":1, "Fe":2, "P":5, "O":-2}) s = t1.apply_transformation(p.struct) t = PartialRemoveSpecieTransformation("Li+", 0.5, PartialRemoveSpecieTransformation.ALGO_COMPLETE) self.assertEqual(len(t.apply_transformation(s, 10)), 6)
def setUp(self): filepath = os.path.join(test_dir, 'POSCAR') poscar = Poscar.from_file(filepath) self.struct = poscar.struct self.mitparamset = MITVaspInputSet() self.mithseparamset = MITHSEVaspInputSet() self.paramset = MaterialsProjectVaspInputSet()
def test_get_atoms(self): if not aio.ase_loaded: raise SkipTest("ASE not present. Skipping...") p = Poscar.from_file(os.path.join(test_dir, 'POSCAR')) structure = p.struct atoms = aio.AseAtomsAdaptor.get_atoms(structure) ase_composition = Composition.from_formula(atoms.get_name()) self.assertEqual(ase_composition, structure.composition)
def forward_final_structure_file(self, childpath, newname="POSCAR"): """Forward the final structure. For VASP, this is the CONTCAR. Args: childpath <str>: Path of child ingredient newname <str>: new name (default 'POSCAR') """ proceed=False workdir=os.path.dirname(self.keywords['name']) sdir=os.path.join(workdir,"structure_index_files") if os.path.exists(sdir): proceed=True if not proceed: return self.copy_a_file(childpath, "CONTCAR", newname) childmeta=Metadata(metafile="%s/metadata.txt" % childpath) child_program=childmeta.read_data("program") if not "vasp" in child_program: #madelung utility or another folder return self.copy_a_file(childpath, "CONTCAR", newname) child_scaling_label=childmeta.read_data("scaling_label") child_defect_label=childmeta.read_data("defect_label") child_neb_label=childmeta.read_data("neb_label") child_phonon_label=childmeta.read_data("phonon_label") if child_scaling_label == None: child_scaling_label = "" if child_defect_label == None: child_defect_label = "" if child_neb_label == None: child_neb_label = "" if child_phonon_label == None: child_phonon_label = "" parentmeta=Metadata(metafile="%s/metadata.txt" % self.keywords['name']) parent_defect_label=parentmeta.read_data("defect_label") parent_neb_label=parentmeta.read_data("neb_label") if parent_defect_label == None: parent_defect_label = "" if parent_neb_label == None: parent_neb_label = "" if (not (child_neb_label == "")) and (not (parent_defect_label == "")): child_defect_label = parent_defect_label if (not (child_phonon_label == "")): if (not (parent_defect_label == "")): child_defect_label = parent_defect_label if (not (parent_neb_label == "")): child_neb_label = parent_neb_label child_defect_label = parent_neb_label.split('-')[0].strip() # always define phonons from first endpoint #get child manifest childmanifest="manifest_%s_%s_%s" % (child_scaling_label, child_defect_label, child_neb_label) #build structure from atom indices using parent name_frac_coords ing_label=os.path.basename(self.keywords['name']) childmeta.write_data("parent",ing_label) mystr=Poscar.from_file("%s/CONTCAR" % self.keywords['name']).structure myatomindex=AtomIndex(structure_index_directory=sdir) if "inducescaling" in childpath: #initial scaled coords have no parent ing_label="original" newstr=myatomindex.graft_new_coordinates_from_manifest(mystr, childmanifest,ing_label) newposcar=Poscar(newstr) newposcar.write_file(os.path.join(childpath,newname)) return
def update_atom_index_for_complete(self): """Update atom index files with positions for the completed ingredient. """ proceed=False mydir = self.keywords['name'] workdir=os.path.dirname(mydir) sdir=os.path.join(workdir,"structure_index_files") if os.path.exists(sdir): proceed=True if not proceed: self.logger.warning("Called update atom index for ingredient %s, but no atom indices exist." % self.keywords['name']) return mymeta=Metadata(metafile="%s/metadata.txt" % mydir) phonon_label = mymeta.read_data("phonon_label") if not (phonon_label == None): #Don't update atom indices for phonons self.logger.debug("Skipping atom index update for phonon calculation %s" % self.keywords['name']) return scaling_label=mymeta.read_data("scaling_label") defect_label=mymeta.read_data("defect_label") neb_label=mymeta.read_data("neb_label") if scaling_label == None: scaling_label = "" if defect_label == None: defect_label = "" if neb_label == None: neb_label = "" if neb_label == "": mystr=Poscar.from_file("%s/CONTCAR" % self.keywords["name"]).structure ing_label=os.path.basename(mydir) manname="manifest_%s_%s_%s" % (scaling_label, defect_label, neb_label) myatomindex=AtomIndex(structure_index_directory=sdir) myatomindex.update_atom_indices_from_structure(mystr, ing_label, manname) else: nebdirs = dirutil.immediate_subdirs(self.keywords["name"]) for mysubdir in nebdirs: if os.path.isfile("%s/%s/CONTCAR" % (self.keywords["name"],mysubdir)): mystr=Poscar.from_file("%s/%s/CONTCAR" % (self.keywords["name"], mysubdir)).structure ing_label=os.path.join(os.path.basename(mydir), mysubdir) for defect_label in neb_label.split("-"): manname="manifest_%s_%s_%s" % (scaling_label, defect_label, neb_label) myatomindex=AtomIndex(structure_index_directory=sdir) myatomindex.update_atom_indices_from_structure(mystr, ing_label, manname) return
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 cif(src="POSCAR"): """ cifファイルを作成 """ srcpos = Poscar.from_file(src) finder = SpacegroupAnalyzer(srcpos.structure) std = finder.get_conventional_standard_structure() cif = CifWriter(std, find_spacegroup=True, symprec=0.1) cif.write_file("poscar.cif")
def _phon_inphon_get_masses(self): """Get the ntypes and masses line for INPHON. Returns: nline, massline nline <str>: NYTPES = <number of atomic types in POSCAR> massline <str>: MASS = <mass1> <mass2> ... """ name=self.keywords['name'] if os.path.isfile(name + "/POSCAR_prePHON"): mypos = Poscar.from_file(name + "/POSCAR_prePHON") else: #not yet modified to strip out the species line. mypos = Poscar.from_file(name + "/POSCAR") sitesym = mypos.site_symbols nline="NTYPES=" + str(len(sitesym)) massline="MASS=" for sym in sitesym: el = pymatgen.core.periodic_table.Element(sym) massline = massline + str(float(el.atomic_mass)) + " " return [nline, massline]
def print_spg(src='POSCAR'): """ space group を return """ srcpos = Poscar.from_file(src) finder = SpacegroupAnalyzer(srcpos.structure, symprec=5e-2, angle_tolerance=8) spg = finder.get_spacegroup_symbol() spg_num = finder.get_spacegroup_number() return spg, spg_num
def _phon_inphon_get_masses(self): """Get the ntypes and masses line for INPHON. Returns: nline, massline nline <str>: NYTPES = <number of atomic types in POSCAR> massline <str>: MASS = <mass1> <mass2> ... """ name = self.keywords['name'] if os.path.isfile(name + "/POSCAR_prePHON"): mypos = Poscar.from_file(name + "/POSCAR_prePHON") else: #not yet modified to strip out the species line. mypos = Poscar.from_file(name + "/POSCAR") sitesym = mypos.site_symbols nline = "NTYPES=" + str(len(sitesym)) massline = "MASS=" for sym in sitesym: el = pymatgen.core.periodic_table.Element(sym) massline = massline + str(float(el.atomic_mass)) + " " return [nline, massline]
def alt_volume(func, src="POSCAR"): """ 体積を変更した POSCAR を作成 """ srcpos = Poscar.from_file(src) elem = get_elements(src) ideal_v = func(elem) srcpos.structure.scale_lattice(ideal_v) dst = "POSCAR_newvol" srcpos.write_file(dst)
def standard(src="POSCAR"): """ standardに変換 """ srcpos = Poscar.from_file(src) finder = SpacegroupAnalyzer(srcpos.structure) std = finder.get_conventional_standard_structure() dstpos = Poscar(std) dst = "POSCAR_std" Cabinet.reserve_file(dst) dstpos.write_file(dst)
def get_final_structure_from_directory(self, mydir=""): """Get the final structure. For VASP, this is the CONTCAR file. Args: mydir <str>: Directory. If no directory is given, use current ingredient directory given as keyword 'name' """ if mydir == "": mydir = self.keywords['name'] return Poscar.from_file("%s/CONTCAR" % mydir).structure
def refined(src="POSCAR"): """ refined poscar を 作成する """ srcpos = Poscar.from_file(src) finder = SpacegroupAnalyzer(srcpos.structure, symprec=5e-1, angle_tolerance=8) std = finder.get_refined_structure() dstpos = Poscar(std) dst = "POSCAR_refined" Cabinet.reserve_file(dst) dstpos.write_file(dst)
def primitive(src="POSCAR"): """ primitiveに変換 """ srcpos = Poscar.from_file(src) finder = SpacegroupAnalyzer(srcpos.structure) prim = finder.get_primitive_standard_structure() dstpos = Poscar(prim) dst = "POSCAR_prim" Cabinet.reserve_file(dst) dstpos.write_file(dst)
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 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 read_xyz(fileobj,n=-1,data=False): """ Function to read multi-atom xyz file with data Inputs: fileobj = String containing file name or file object n = Integer indicating number for structure from xyz file to read. Default is last structure in file. Or String=='All' which will output all structures in file data = True/False boolean indicating whether or not to output any data strings read from xyz file Outputs: atmslist = ASE Atoms class object containing structure from file or list of Atoms objects if n=='All' datalist(Optional) = String of data read from xyz file or list of data strings read from xyz file """ try: from pymatgen.io.vaspio import Poscar mystructure = Poscar.from_file(fileobj).structure from pymatgen.io.aseio import AseAtomsAdaptor myatoms = AseAtomsAdaptor.get_atoms(mystructure) return myatoms except: if isinstance(fileobj, str): fileobj = open(fileobj,'r') lines = fileobj.readlines() atmslist = [] datalist = [] while len(lines)>0: natoms = int(lines[0]) datalist.append(lines[1]) atm1 = Atoms() i =- 1 for i in range(natoms): a = lines[i+2].split() sym = a[0] position = [float(a[1]),float(a[2]),float(a[3])] atm1.append(Atom(symbol=sym,position=position)) atmslist.append(atm1) lines = lines[i+3::] if n == 'All': if data == True: return atmslist, datalist else: return atmslist else: if data == True: return atmslist[n],datalist[n] else: return atmslist[n]
def test_check_correct(self): #NOTE: the vasprun here has had projected and partial eigenvalues removed subdir = os.path.join(test_dir, "max_force") os.chdir(subdir) shutil.copy("INCAR", "INCAR.orig") shutil.copy("POSCAR", "POSCAR.orig") h = MaxForceErrorHandler() self.assertTrue(h.check()) d = h.correct() self.assertEqual(d["errors"], ['MaxForce']) os.remove(os.path.join(subdir, "error.1.tar.gz")) incar = Incar.from_file('INCAR') poscar = Poscar.from_file('POSCAR') contcar = Poscar.from_file('CONTCAR') shutil.move("INCAR.orig", "INCAR") shutil.move("POSCAR.orig", "POSCAR") self.assertEqual(poscar.structure, contcar.structure) self.assertAlmostEqual(incar['EDIFF'], 0.00075)
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 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 _phon_poscar_setup(self): """Set up a PHON POSCAR file. Strip out the "elements" line (that is, use VASP version 4 format. Also strip out anything beneath the atoms line. """ name = self.keywords['name'] pospath = os.path.join(name, "POSCAR") prepath = os.path.join(name, "POSCAR_prePHON") if os.path.isfile(pospath): #Already done. Return. return my_poscar = Poscar.from_file(prepath) my_poscar.selective_dynamics=None #unset SD if it is set my_poscar.velocities=None #unset velocities dirutil.lock_directory(name) my_poscar.write_file(pospath) dirutil.unlock_directory(name) #pick up a copy and strip out the elements line. mypfile = MASTFile(pospath) myline6=mypfile.get_line_number(6) if myline6.strip().split()[0].isalpha: mypfile.modify_file_by_line_number(6,"D") mypfile.to_file(pospath) return
""" Get input data first """ parser = argparse.ArgumentParser() parser.add_argument("-i", "--input", help="file with calculation variables", required=True, metavar="FILE") parser.add_argument("-p", "--parent", help="parent file in vasp POSCAR format", required=True, metavar="FILE") args = parser.parse_args() invars = Conf(args.input) ''' Import initial parent structure ''' poscar = Poscar.from_file(args.parent) parent_struct = poscar.structure os.chdir(invars.run_dir) if invars.restart == ".FALSE.": with open("ORDERING_OUTPUT.txt", 'a') as file: file.write("Input Structure Info:\n\n") file.write("-------------------------------------------------------------------------------------\n\n") file.write("{}\n\n".format(parent_struct)) file.write("-------------------------------------------------------------------------------------\n\n") def end_status(status): if status == 'success': with open("ORDERING_OUTPUT.txt", 'a') as file: file.write("Yor job has ended sucessfully\n")
from PathFinder.pathFinder import NEBPathfinder, ChgcarPotential if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-s1', type=str, help='starting point CONTCAR') parser.add_argument('-s2', type=str, help='ending point CONTCAR') parser.add_argument('-e', type=str, help='diffusing cation') parser.add_argument('-n', type=int, default=8, help='number of interpolated images') parser.add_argument('-chg', type=str, help='CHGCAR for pathFinder') arg = parser.parse_args() s1 = Poscar.from_file(arg.s1).structure s2 = Poscar.from_file(arg.s2).structure chg = Chgcar.from_file(arg.chg) relax_sites = [] for i, site in enumerate(s1.sites): if site.specie == Element(arg.e): relax_sites.append(i) pf = NEBPathfinder(s1, s2, relax_sites=relax_sites, v=ChgcarPotential(chg).get_v(), n_images=(3 * arg.n)) images = pf.images
] if len(structures_list) == 0: print('no structures found') 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:
def process_killed_run(cls, dir_name): """ Process a killed vasp run. """ fullpath = os.path.abspath(dir_name) logger.info("Processing Killed run " + fullpath) d = {"dir_name": fullpath, "state": "killed", "oszicar": {}} for f in os.listdir(dir_name): filename = os.path.join(dir_name, f) if fnmatch(f, "INCAR*"): try: incar = Incar.from_file(filename) d["incar"] = incar.to_dict d["is_hubbard"] = incar.get("LDAU", False) if d["is_hubbard"]: us = incar.get("LDAUU", []) js = incar.get("LDAUJ", []) if sum(us) == 0 and sum(js) == 0: d["is_hubbard"] = False d["hubbards"] = {} else: d["hubbards"] = {} if d["is_hubbard"]: d["run_type"] = "GGA+U" elif incar.get("LHFCALC", False): d["run_type"] = "HF" else: d["run_type"] = "GGA" except Exception as ex: print str(ex) logger.error( "Unable to parse INCAR for killed run {}.".format( dir_name)) elif fnmatch(f, "KPOINTS*"): try: kpoints = Kpoints.from_file(filename) d["kpoints"] = kpoints.to_dict except: logger.error( "Unable to parse KPOINTS for killed run {}.".format( dir_name)) elif fnmatch(f, "POSCAR*"): try: s = Poscar.from_file(filename).structure comp = s.composition el_amt = s.composition.get_el_amt_dict() d.update({ "unit_cell_formula": comp.to_dict, "reduced_cell_formula": comp.to_reduced_dict, "elements": list(el_amt.keys()), "nelements": len(el_amt), "pretty_formula": comp.reduced_formula, "anonymous_formula": comp.anonymized_formula, "nsites": comp.num_atoms, "chemsys": "-".join(sorted(el_amt.keys())) }) d["poscar"] = s.to_dict except: logger.error( "Unable to parse POSCAR for killed run {}.".format( dir_name)) elif fnmatch(f, "POTCAR*"): try: potcar = Potcar.from_file(filename) d["pseudo_potential"] = { "functional": "pbe", "pot_type": "paw", "labels": potcar.symbols } except: logger.error( "Unable to parse POTCAR for killed run in {}.".format( dir_name)) elif fnmatch(f, "OSZICAR"): try: d["oszicar"]["root"] = \ Oszicar(os.path.join(dir_name, f)).to_dict except: logger.error( "Unable to parse OSZICAR for killed run in {}.".format( dir_name)) elif re.match("relax\d", f): if os.path.exists(os.path.join(dir_name, f, "OSZICAR")): try: d["oszicar"][f] = Oszicar( os.path.join(dir_name, f, "OSZICAR")).to_dict except: logger.error("Unable to parse OSZICAR for killed " "run in {}.".format(dir_name)) return d
#!/usr/bin/env python from pymatgen.io.vaspio import Poscar import cProfile import pstats import os import logging logging.basicConfig(level=logging.DEBUG) p = Poscar.from_file("../test_files/POSCAR.LiFePO4", check_for_POTCAR=False) s = p.structure def test(): nn = s.get_all_neighbors(20) print len(nn) def chgcar_test(): from pymatgen.io.vaspio import Chgcar c = Chgcar.from_file("../test_files/CHGCAR.noncubic") print c.get_integrated_diff(1, 2.5, 3) def vasprun_test(): from pymatgen.io.vaspio import Vasprun v = Vasprun("../test_files/vasprun.xml") print v.final_energy def matcher_test(): p = Poscar.from_file("../test_files/POSCAR.Li2O") s = p.structure from pymatgen.analysis.structure_matcher import StructureMatcher
def matcher_test(): p = Poscar.from_file("../test_files/POSCAR.Li2O") s = p.structure from pymatgen.analysis.structure_matcher import StructureMatcher print StructureMatcher().fit(s, s)