def test_continue(self): # Test the continuation functionality with cd(os.path.join(test_dir, 'postprocess')): # Test default functionality with ScratchDir('.', copy_from_current_on_enter=True) as d: v = VaspJob("hello", auto_continue=True) v.setup() self.assertTrue(os.path.exists("continue.json"), "continue.json not created") v.setup() self.assertEqual(Poscar.from_file("CONTCAR").structure, Poscar.from_file("POSCAR").structure) self.assertEqual(Incar.from_file('INCAR')['ISTART'], 1) v.postprocess() self.assertFalse(os.path.exists("continue.json"), "continue.json not deleted after postprocessing") # Test explicit action functionality with ScratchDir('.', copy_from_current_on_enter=True) as d: v = VaspJob("hello", auto_continue=[{"dict": "INCAR", "action": {"_set": {"ISTART": 1}}}]) v.setup() v.setup() self.assertNotEqual(Poscar.from_file("CONTCAR").structure, Poscar.from_file("POSCAR").structure) self.assertEqual(Incar.from_file('INCAR')['ISTART'], 1) v.postprocess()
def _verify_inputs(self): user_incar = Incar.from_file(os.path.join(os.getcwd(), "INCAR")) ref_incar = Incar.from_file(os.path.join(self["ref_dir"], "inputs", "INCAR")) # perform some BASIC tests # check INCAR params_to_check = self.get("params_to_check", []) defaults = {"ISPIN": 1, "ISMEAR": 1, "SIGMA": 0.2} for p in params_to_check: if user_incar.get(p, defaults.get(p)) != ref_incar.get(p, defaults.get(p)): raise ValueError("INCAR value of {} is inconsistent!".format(p)) # check KPOINTS user_kpoints = Kpoints.from_file(os.path.join(os.getcwd(), "KPOINTS")) ref_kpoints = Kpoints.from_file(os.path.join(self["ref_dir"], "inputs", "KPOINTS")) if user_kpoints.style != ref_kpoints.style or user_kpoints.num_kpts != ref_kpoints.num_kpts: raise ValueError("KPOINT files are inconsistent! Paths are:\n{}\n{}".format( os.getcwd(), os.path.join(self["ref_dir"], "inputs"))) # check POSCAR user_poscar = Poscar.from_file(os.path.join(os.getcwd(), "POSCAR")) ref_poscar = Poscar.from_file(os.path.join(self["ref_dir"], "inputs", "POSCAR")) if user_poscar.natoms != ref_poscar.natoms or user_poscar.site_symbols != ref_poscar.site_symbols: raise ValueError("POSCAR files are inconsistent! Paths are:\n{}\n{}".format( os.getcwd(), os.path.join(self["ref_dir"], "inputs"))) # check POTCAR user_potcar = Potcar.from_file(os.path.join(os.getcwd(), "POTCAR")) ref_potcar = Potcar.from_file(os.path.join(self["ref_dir"], "inputs", "POTCAR")) if user_potcar.symbols != ref_potcar.symbols: raise ValueError("POTCAR files are inconsistent! Paths are:\n{}\n{}".format( os.getcwd(), os.path.join(self["ref_dir"], "inputs"))) logger.info("RunVaspFake: verified inputs successfully")
def _verify_inputs(self): """Validation of input files under user NEB directory.""" user_incar = Incar.from_file(os.path.join(self.user_dir, "INCAR")) ref_incar = Incar.from_file(os.path.join(self.ref_dir_input, "INCAR")) # Check INCAR params_to_check = self.get("params_to_check", []) defaults = {"ICHAIN": 0, "LCLIMB": True} for p in params_to_check: if user_incar.get(p, defaults.get(p)) != ref_incar.get(p, defaults.get(p)): raise ValueError("INCAR value of {} is inconsistent!".format(p)) # Check KPOINTS user_kpoints = Kpoints.from_file(os.path.join(self.user_dir, "KPOINTS")) ref_kpoints = Kpoints.from_file(os.path.join(self.ref_dir_input, "KPOINTS")) if user_kpoints.style != ref_kpoints.style or user_kpoints.num_kpts != ref_kpoints.num_kpts: raise ValueError("KPOINT files are inconsistent! " "Paths are:\n{}\n{} with kpts = {} {}".format( self.user_dir, self.ref_dir_input, user_kpoints, ref_kpoints)) # Check POTCAR user_potcar = Potcar.from_file(os.path.join(self.user_dir, "POTCAR")) ref_potcar = Potcar.from_file(os.path.join(self.ref_dir_input, "POTCAR")) if user_potcar.symbols != ref_potcar.symbols: raise ValueError("POTCAR files are inconsistent! " "Paths are:\n{}\n{}".format(self.user_dir, self.ref_dir_input)) # Check POSCARs for u, r in zip(self.user_sdir, self.ref_sdir_input): user_poscar = Poscar.from_file(os.path.join(u, "POSCAR")) ref_poscar = Poscar.from_file(os.path.join(r, "POSCAR")) if user_poscar.natoms != ref_poscar.natoms or \ user_poscar.site_symbols != ref_poscar.site_symbols: raise ValueError("POSCAR files are inconsistent! Paths are:\n{}\n{}".format(u, r))
def run_task(self, fw_spec): transformations = [] transformation_params = self.get("transformation_params", [{} for i in range(len(self["transformations"]))]) for t in self["transformations"]: for m in [ "advanced_transformations", "defect_transformations", "site_transformations", "standard_transformations", ]: mod = import_module("pymatgen.transformations.{}".format(m)) try: t_cls = getattr(mod, t) except AttributeError: continue t_obj = t_cls(**transformation_params.pop(0)) transformations.append(t_obj) structure = ( self["structure"] if "prev_calc_dir" not in self else Poscar.from_file(os.path.join(self["prev_calc_dir"], "POSCAR")).structure ) ts = TransformedStructure(structure) transmuter = StandardTransmuter([ts], transformations) final_structure = transmuter.transformed_structures[-1].final_structure.copy() vis_orig = self["vasp_input_set"] vis_dict = vis_orig.as_dict() vis_dict["structure"] = final_structure.as_dict() vis_dict.update(self.get("override_default_vasp_params", {}) or {}) vis = vis_orig.__class__.from_dict(vis_dict) vis.write_input(".")
def test_run_subfolders(self): #raise SkipTest ingdir="%s/writedir/single_label1" % testdir recipedir="%s/writedir" % testdir topmetad = MASTFile("files/top_metadata_single") topmetad.data.append("origin_dir = %s/files\n" % testdir) #give origin directory topmetad.to_file("writedir/metadata.txt") metad = MASTFile("files/metadata_single") metad.to_file("%s/metadata.txt" % ingdir) kdict=dict() kdict['mast_program'] = 'vasp' kdict['mast_kpoints'] = [2,2,2,"M"] kdict['mast_xc'] = 'pw91' my_structure = Poscar.from_file("files/perfect_structure").structure for subfolder in ['sub1','sub2','sub3','sub4']: subname = "%s/%s" % (ingdir, subfolder) os.mkdir(subname) shutil.copy("files/metadata_single","%s/metadata.txt" % subname) mywr = ChopIngredient(name=subname, program_keys = kdict, structure=my_structure) mywr.write_singlerun() myri = ChopIngredient(name=ingdir,program_keys=kdict, structure=my_structure) myri.run_subfolders() self.assertFalse(myri.checker.is_ready_to_run()) for subfolder in ['sub1','sub2','sub3','sub4']: subname = "%s/%s" % (ingdir, subfolder) myri.checker.keywords['name'] = subname self.assertTrue(myri.checker.is_ready_to_run()) mysubmit = MASTFile("%s/submitlist" % self.test_control) self.assertEquals(mysubmit.data[0], "%s/sub1\n" % ingdir) self.assertEquals(mysubmit.data[1], "%s/sub2\n" % ingdir) self.assertEquals(mysubmit.data[2], "%s/sub3\n" % ingdir) self.assertEquals(mysubmit.data[3], "%s/sub4\n" % ingdir)
def run_task(self, fw_spec): transformations = [] transformation_params = self.get("transformation_params", [{} for i in range(len(self["transformations"]))]) for t in self["transformations"]: found = False for m in ["advanced_transformations", "defect_transformations", "site_transformations", "standard_transformations"]: mod = import_module("pymatgen.transformations.{}".format(m)) try: t_cls = getattr(mod, t) except AttributeError: continue t_obj = t_cls(**transformation_params.pop(0)) transformations.append(t_obj) found = True if not found: raise ValueError("Could not find transformation: {}".format(t)) # TODO: @matk86 - should prev_calc_dir use CONTCAR instead of POSCAR? Note that if # current dir, maybe it is POSCAR indeed best ... -computron structure = self['structure'] if not self.get('prev_calc_dir', None) else \ Poscar.from_file(os.path.join(self['prev_calc_dir'], 'POSCAR')).structure ts = TransformedStructure(structure) transmuter = StandardTransmuter([ts], transformations) final_structure = transmuter.transformed_structures[-1].final_structure.copy() vis_orig = self["vasp_input_set"] vis_dict = vis_orig.as_dict() vis_dict["structure"] = final_structure.as_dict() vis_dict.update(self.get("override_default_vasp_params", {}) or {}) vis = vis_orig.__class__.from_dict(vis_dict) vis.write_input(".") dumpfn(transmuter.transformed_structures[-1], "transformations.json")
def setUpClass(cls): if not os.environ.get("VASP_PSP_DIR"): os.environ["VASP_PSP_DIR"] = os.path.join(module_dir, "reference_files") print( 'Note: This system is not set up to run VASP jobs. ' 'Please set your VASP_PSP_DIR environment variable.') cls.struct_si = PymatgenTest.get_structure("Si") cls.ref_incar = Incar.from_file( os.path.join(module_dir, "reference_files", "setup_test", "INCAR")) cls.ref_poscar = Poscar.from_file( os.path.join(module_dir, "reference_files", "setup_test", "POSCAR")) cls.ref_potcar = Potcar.from_file( os.path.join(module_dir, "reference_files", "setup_test", "POTCAR")) cls.ref_kpoints = Kpoints.from_file( os.path.join(module_dir, "reference_files", "setup_test", "KPOINTS")) cls.ref_incar_preserve = Incar.from_file(os.path.join(module_dir, "reference_files", "preserve_incar", "INCAR"))
def full_opt_run(cls, vasp_cmd, auto_npar=True, vol_change_tol=0.05, max_steps=10): """ Returns a generator of jobs for a full optimization run. Basically, this runs an infinite series of geometry optimization jobs until the % vol change in a particular optimization is less than vol_change_tol. Args: vasp_cmd (str): Command to run vasp as a list of args. For example, if you are using mpirun, it can be something like ["mpirun", "pvasp.5.2.11"] auto_npar (bool): Whether to automatically tune NPAR to be sqrt( number of cores) as recommended by VASP for DFT calculations. Generally, this results in significant speedups. Defaults to True. Set to False for HF, GW and RPA calculations. vol_change_tol (float): The tolerance at which to stop a run. Defaults to 0.05, i.e., 5%. max_steps (int): The maximum number of runs. Defaults to 10 ( highly unlikely that this limit is ever reached). Returns: Generator of jobs. """ for i in xrange(max_steps): if i == 0: settings = None backup = True else: backup = False initial = Poscar.from_file("POSCAR").structure final = Poscar.from_file("CONTCAR").structure vol_change = (final.volume - initial.volume) / initial.volume logging.info("Vol change = %.1f %%!" % (vol_change * 100)) if abs(vol_change) < vol_change_tol: logging.info("Stopping optimization!") break else: settings = [ {"dict": "INCAR", "action": {"_set": {"ISTART": 1}}}, {"file": "CONTCAR", "action": {"_file_copy": {"dest": "POSCAR"}}}] logging.info("Generating job = %d!" % (i+1)) yield VaspJob(vasp_cmd, final=False, backup=backup, suffix=".relax%d" % (i+1), auto_npar=auto_npar, settings_override=settings)
def five(src): """ VASP ver.5 のフォーマットに変換 元素名を 5 行目に追加 """ srcpos = Poscar.from_file(src) dst = "POSCAR_five" srcpos.write_file(dst)
def _verify_files(self): self.assertEqual(Incar.from_file(os.path.join(module_dir, "INCAR")), self.ref_incar) self.assertEqual(str(Poscar.from_file(os.path.join(module_dir, "POSCAR"))), str(self.ref_poscar)) self.assertEqual(Potcar.from_file(os.path.join(module_dir, "POTCAR")).symbols, self.ref_potcar.symbols) self.assertEqual(str(Kpoints.from_file(os.path.join(module_dir, "KPOINTS"))), str(self.ref_kpoints))
def ver5(src='POSCAR'): """ ver 5 の形式に変換 (POTCAR を読んで元素名を追加) """ srcpos = Poscar.from_file(src) dst = 'POSCAR_five' srcpos.write_file(dst)
def get_elements(src): """ 元素ラベルを出力 """ srcpos = Poscar.from_file(src) elements = [x.symbol for x in srcpos.structure.species] elem_counter = Counter(elements) return elem_counter
def checkrelax_single(path, src_ini="posfinal", src_fin="posfinal3"): """ 緩和で構造が歪んでいないかを check """ 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 cif(src): """ cifファイルを作成 """ srcpos = Poscar.from_file(src) finder = SpacegroupAnalyzer(srcpos.structure) std_str = finder.get_conventional_standard_structure() std_cif = CifWriter(std_str, symprec=0.1) std_cif.write_file("poscar.cif")
def check(self): try: oszicar = Oszicar(self.output_filename) n = len(Poscar.from_file(self.input_filename).structure) max_dE = max([s['dE'] for s in oszicar.ionic_steps[1:]]) / n if max_dE > self.dE_threshold: return True except: return False
def cif(src='POSCAR'): """ cifファイルを作成 """ srcpos = Poscar.from_file(src) finder = SpacegroupAnalyzer(srcpos.structure) std_str = finder.get_conventional_standard_structure() cif_obj = CifWriter(std_str, symprec=0.1) cif_obj.write_file('poscar.cif')
def _verify_files(self, skip_kpoints=False, preserve_incar=False): if not preserve_incar: self.assertEqual(Incar.from_file(os.path.join(module_dir, "INCAR")), self.ref_incar) self.assertEqual(str(Poscar.from_file(os.path.join(module_dir, "POSCAR"))), str(self.ref_poscar)) self.assertEqual((Potcar.from_file(os.path.join(module_dir, "POTCAR"))).symbols, self.ref_potcar.symbols) if not skip_kpoints: self.assertEqual(str(Kpoints.from_file(os.path.join(module_dir, "KPOINTS"))), str(self.ref_kpoints)) else: self.assertEqual(Incar.from_file(os.path.join(module_dir, "INCAR")), self.ref_incar_preserve)
def get_structure(filename): if filename.lower().endswith('.cif'): structure = CifParser(filename).get_structures()[0] lattice = pmg.Lattice.from_parameters(*structure.lattice.abc, *structure.lattice.angles) return pmg.Structure(lattice, structure.species, structure.frac_coords, coords_are_cartesian=False) elif filename.lower().endswith('poscar'): return Poscar.from_file(filename).structure else: raise ValueError('Cannot determine file type from filename [.cif, poscar]')
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_space_group_symbol() spg_num = finder.get_space_group_number() return spg, spg_num
def print_spg(src): """ space group を表示する """ 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 test_image_num(self): module_dir = os.path.dirname(os.path.abspath(__file__)) test_file_dir = os.path.join(module_dir, "..", "..", "..", "test_files", "path_finder") start_s = Poscar.from_file(os.path.join(test_file_dir, 'LFP_POSCAR_s')).structure end_s = Poscar.from_file(os.path.join(test_file_dir, 'LFP_POSCAR_e')).structure chg = Chgcar.from_file(os.path.join(test_file_dir, 'LFP_CHGCAR.gz')) moving_cation_specie = Element('Li') relax_sites = [] for site_i, site in enumerate(start_s.sites): if site.specie == moving_cation_specie: relax_sites.append(site_i) pf = NEBPathfinder(start_s, end_s, relax_sites=relax_sites, v=ChgcarPotential(chg).get_v(), n_images=(8 * 3)) images = [] for i, image in enumerate(pf.images): if i % 3 == 0: images.append(image) self.assertEqual(len(images), 9)
def refined(src): """ refined poscar を 作成する """ srcpos = Poscar.from_file(src) finder = SpacegroupAnalyzer(srcpos.structure, symprec=5e-1, angle_tolerance=8) scr_std = finder.get_refined_structure() dstpos = Poscar(scr_std) dst = "POSCAR_refined" Cabinet.reserve_file(dst) dstpos.write_file(dst)
def prim(src): """ primitive cell に変換 """ srcpos = Poscar.from_file(src) finder = SpacegroupAnalyzer(srcpos.structure) prim_str = finder.get_primitive_standard_structure() dstpos = Poscar(prim_str) dst = 'POSCAR_prim' Cabinet.reserve_file(dst) dstpos.write_file(dst)
def std(src='POSCAR'): """ conventional standard cell に変換 """ srcpos = Poscar.from_file(src) finder = SpacegroupAnalyzer(srcpos.structure) std_str = finder.get_conventional_standard_structure() dstpos = Poscar(std_str) dst = 'POSCAR_std' Cabinet.reserve_file(dst) dstpos.write_file(dst)
def of_poscar(cls, poscar_path, initial_pressure=0.0, initial_temperature=1000.0, target_pressure=0.0, target_temperature=1000.0, alpha=10e-5, beta=10e-7): """ Convenience constructor that accepts a poscar file as input """ poscar = Poscar.from_file(poscar_path) return cls(poscar.structure, initial_pressure=initial_pressure, initial_temperature=initial_temperature, target_pressure=target_pressure, target_temperature=target_temperature, alpha=alpha, beta=beta, poscar=poscar)
def test_run_neb_subfolders(self): #raise SkipTest ingdir="%s/writedir/neb_labelinit-labelfin_stat" % testdir recipedir="%s/writedir" % testdir topmetad = MASTFile("files/top_metadata_neb") topmetad.data.append("origin_dir = %s/files\n" % testdir) #give origin directory topmetad.to_file("writedir/metadata.txt") metad = MASTFile("files/metadata_neb") metad.to_file("%s/metadata.txt" % ingdir) kdict=dict() kdict['mast_program'] = 'vasp' kdict['mast_kpoints'] = [2,2,2,"M"] kdict['mast_xc'] = 'pw91' neblines = list() neblines.append(["Cr","0.0 0.9 0.8","0.0 0.8 0.7"]) neblines.append(["Cr","0.4 0.2 0.1","0.3 0.3 0.2"]) neblines.append(["Cr","0.29 0.05 0.05","0.01 0.01 0.98"]) neblines.append(["Ni","0.61 0.99 0.98","0.25 0.01 0.97"]) kdict['mast_neb_settings']=dict() kdict['mast_neb_settings']['lines']=neblines kdict['mast_neb_settings']['images']=3 str_00 = MASTFile("files/POSCAR_00") str_00.to_file("%s/parent_structure_labelinit" % ingdir) str_04 = MASTFile("files/POSCAR_04") str_04.to_file("%s/parent_structure_labelfin" % ingdir) str_01 = MASTFile("files/POSCAR_01") str_01.to_file("%s/parent_structure_labelinit-labelfin_01" % ingdir) str_02 = MASTFile("files/POSCAR_02") str_02.to_file("%s/parent_structure_labelinit-labelfin_02" % ingdir) str_03 = MASTFile("files/POSCAR_03") str_03.to_file("%s/parent_structure_labelinit-labelfin_03" % ingdir) en_00 = MASTFile("files/OSZICAR_00") en_00.to_file("%s/parent_energy_labelinit" % ingdir) en_04 = MASTFile("files/OSZICAR_04") en_04.to_file("%s/parent_energy_labelfin" % ingdir) my_structure = Poscar.from_file("files/perfect_structure").structure mywr = ChopIngredient(name=ingdir, program_keys = kdict, structure=my_structure) mywr.write_neb_subfolders() myri = ChopIngredient(name=ingdir,program_keys=kdict, structure=my_structure) myri.run_neb_subfolders() mysubmit = MASTFile("%s/submitlist" % self.test_control) myri.checker.keywords['name'] = "%s/00" % ingdir self.assertFalse(myri.checker.is_ready_to_run()) #do not run endpoints again myri.checker.keywords['name'] = "%s/01" % ingdir self.assertTrue(myri.checker.is_ready_to_run()) myri.checker.keywords['name'] = "%s/02" % ingdir self.assertTrue(myri.checker.is_ready_to_run()) myri.checker.keywords['name'] = "%s/03" % ingdir self.assertTrue(myri.checker.is_ready_to_run()) myri.checker.keywords['name'] = "%s/04" % ingdir self.assertFalse(myri.checker.is_ready_to_run()) #do not run endpoints again self.assertEquals(mysubmit.data[0], "%s/01\n" % ingdir) self.assertEquals(mysubmit.data[1], "%s/02\n" % ingdir) self.assertEquals(mysubmit.data[2], "%s/03\n" % ingdir)
def test_run_scale(self): #raise SkipTest ingdir="%s/writedir/single_label1" % testdir recipedir="%s/writedir" % testdir topmetad = MASTFile("files/top_metadata_single") topmetad.data.append("origin_dir = %s/files\n" % testdir) #give origin directory topmetad.to_file("writedir/metadata.txt") metad = MASTFile("files/metadata_single") metad.data.append("defect_label = label1\n") metad.data.append("scaling_size = [2,2,2]\n") metad.to_file("%s/metadata.txt" % ingdir) kdict=dict() kdict['mast_program'] = 'vasp' my_structure = Poscar.from_file("files/POSCAR_perfect").structure myperf = MASTFile("files/POSCAR_perfect") myperf.to_file("%s/POSCAR" % ingdir) myri = ChopIngredient(name=ingdir,program_keys=kdict, structure=my_structure) myri.run_scale() my_scaled = Poscar.from_file("%s/CONTCAR" % ingdir).structure.get_sorted_structure() scaled_compare = Poscar.from_file("files/POSCAR_scaled").structure.get_sorted_structure() self.assertEquals(my_scaled, scaled_compare)
def test_run_strain(self): #raise SkipTest ingdir="%s/writedir/single_label1" % testdir recipedir="%s/writedir" % testdir topmetad = MASTFile("files/top_metadata_single") topmetad.data.append("origin_dir = %s/files\n" % testdir) #give origin directory topmetad.to_file("writedir/metadata.txt") metad = MASTFile("files/metadata_single") metad.to_file("%s/metadata.txt" % ingdir) kdict=dict() kdict['mast_program'] = 'vasp' kdict['mast_strain']=" 0.98 0.92 1.03 \n" my_structure = Poscar.from_file("files/POSCAR_perfect").structure myunstrained = MASTFile("files/POSCAR_unstrained") myunstrained.to_file("%s/POSCAR" % ingdir) myri = ChopIngredient(name=ingdir,program_keys=kdict, structure=my_structure) myri.run_strain() my_strained = Poscar.from_file("%s/CONTCAR" % ingdir).structure strained_compare = Poscar.from_file("files/POSCAR_strained").structure self.assertEquals(my_strained, strained_compare) self.assertFalse(os.path.isfile("%s/submitlist" % self.test_control))
def checkrelax_single(path, ini, fin): """ 構造緩和による変形の大きさを出力 """ dirc = path initial = Poscar.from_file( os.path.join(dirc, ini)).structure.as_dict()['lattice'] final = Poscar.from_file( os.path.join(dirc, 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 refined(src='POSCAR'): """ refined cell を 作成する """ srcpos = Poscar.from_file(src) finder = SpacegroupAnalyzer(srcpos.structure, symprec=5e-1, angle_tolerance=8) std_str = finder.get_refined_structure() dstpos = Poscar(std_str) dst = 'POSCAR_refined' Cabinet.reserve_file(dst) dstpos.write_file(dst)
def structure(s): if isinstance(s, Structure): return s elif isinstance(s, Poscar): return s.structure elif isinstance(s, str): return Poscar.from_file(s).structure else: raise TypeError
structures_list = [file for file in next(os.walk('.'))[2] if file.endswith(".cif")] 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:
from copy import deepcopy from pymatgen.io.vasp import Poscar if __name__ == "__main__": Module_Number = int(5) Situation_Number = int(3) Site = "Substitutional" Diffusion_Atoms = ['Al', 'Cr', 'Mo', 'Nb', 'Sn', 'Ti', 'Zr'] Diffusion_Positions = ['a', 'b', 'i'] for Diffusion_Atom in Diffusion_Atoms: for Diffusion_Position in Diffusion_Positions: PATH_CONTCAR = "/mnt/c/Users/jackx/OneDrive/Calculation_Data/TC17_TI80/Optimistic_Results/M{0}_S{1}/{2}/{3}/{4}/CONTCAR".format( Module_Number, Situation_Number, Site, Diffusion_Atom, Diffusion_Position) CONTCAR_structure = Poscar.from_file(PATH_CONTCAR).structure Atoms_number = CONTCAR_structure.num_sites Solute = deepcopy(CONTCAR_structure) Solvent = deepcopy(CONTCAR_structure) Mixture = deepcopy(CONTCAR_structure) Solute.remove_sites(range(0, Atoms_number - 1)) Solvent.remove_sites(range(Atoms_number - 1, Atoms_number)) PATH_Formation = "/mnt/c/Users/jackx/OneDrive/Calculation_Data/TC17_TI80/Bonding_Energy/M{0}_S{1}/{2}/{3}/{4}/".format( Module_Number, Situation_Number, Site, Diffusion_Atom, Diffusion_Position) if os.path.exists(PATH_Formation): shutil.rmtree(PATH_Formation) os.makedirs(PATH_Formation) Solute.to(filename='{}POSCAR_Solute'.format(PATH_Formation)) Solute.to(filename='{}POSCAR_Solute.cif'.format(PATH_Formation)) Solvent.to(filename='{}POSCAR_Solvent'.format(PATH_Formation))
def molecular(self, name): import os import numpy as np from pymatgen.io.phonopy import get_phonopy_structure import pymatgen as pmg from pymatgen.io.vasp.outputs import Vasprun from pymatgen.io.vasp import Poscar from phonopy import Phonopy from phonopy.structure.atoms import Atoms as PhonopyAtoms import csv import pandas as pd import matplotlib.pyplot as plt os.chdir(self.dire) print(os.getcwd()) poscar = Poscar.from_file("POSCAR") structure = poscar.structure scell = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] vrun = Vasprun("vasprun.xml") phonopyAtoms = get_phonopy_structure(structure) phonon = Phonopy(phonopyAtoms, scell) phonon.set_force_constants(-vrun.force_constants) labels = ["$\\Gamma$", "X", "U", "K", "$\\Gamma$", "L", "W"] bands = [] # path 1 q_start = np.array([0.5, 0.5, 0.0]) q_end = np.array([0.0, 0.0, 0.0]) band = [] for i in range(51): band.append(q_start + (q_end - q_start) / 50 * i) bands.append(band) # path 2 q_start = np.array([0.0, 0.0, 0.0]) q_end = np.array([0.5, 0.0, 0.0]) band = [] for i in range(51): band.append(q_start + (q_end - q_start) / 50 * i) bands.append(band) phonon.set_band_structure(bands, labels=labels) # phonon.plot_band_structure().show() mesh = [31, 31, 31] phonon.set_mesh(mesh) phonon.set_total_DOS() phonon.write_total_DOS() # phonon.plot_total_DOS().show() # c = np.fromfile('total_dos.dat', dtype=float) datContent = [ i.strip().split() for i in open("./total_dos.dat").readlines() ] del datContent[0] x_ax = [] y_ax = [] for i in datContent: x_ax.append(1 / ((3 * (10**8) / (float(i[0]) * (10**12))) * 100)) y_ax.append(float(i[1])) da = {'Density of states': x_ax, 'Frequency': y_ax} df = pd.DataFrame(da) #构造原始数据文件 df.to_excel("Wave number.xlsx") #生成Excel文件,并存到指定文件路径下 fig, ax = plt.subplots() line1 = ax.plot(x_ax, y_ax, label=name) ax.set_xlim([4500, 200]) # 以下是XRD图片的格式设置 #设置横纵坐标的名称以及对应字体格式 font2 = { 'family': 'Times New Roman', 'weight': 'bold', } plt.xlabel('Wavenumber ($\mathregular{cm^-}$$\mathregular{^1}$)', font2) plt.ylabel('Density of states', font2) #不显示Y轴的刻度 plt.yticks([]) #设置图例对应格式和字体 font1 = { 'family': 'Times New Roman', 'weight': 'bold', } ax.legend(edgecolor='none', prop=font1) plt.legend(edgecolor='none', prop=font1) # plt.set_facecolor('none') ax.set_facecolor('none') #存储为 fig.savefig('D:\Desktop\python image\cal_FTIR.png', bbox_inches='tight', transparent=True, dpi=300, format='png') #指定分辨率,边界紧,背景透明 plt.show()
from pymatgen.io.vasp import Poscar import pandas as pd # Purpose: This script is similar to the 'vn POSCAR' command # The difference is that I sort the coordinates along the b direction __author__ = "Yue-Wen FANG" __maintainer__ = "Yue-Wen FANG" __email__ = "*****@*****.**" __status__ = "Development" __creation_date__ = "September 13th, 2018" # yourfile = input('Choose a file: ') # p = Poscar.from_file(yourfile) p = Poscar.from_file('./SrTiO3-BiBaTi2O6.vasp') structure_summary = p.structure natoms_list = p.natoms sum_natoms = sum(natoms_list[0:len(natoms_list)]) coordinates = p.structure[0:sum_natoms] fractional_coord_list = [] for i in coordinates: fractional_coord_list.append(i.frac_coords) df = pd.DataFrame( { 'frac_coordinates': fractional_coord_list, 'number': range(1, sum_natoms + 1) }, index=range(1, sum_natoms + 1))
# system name on file file_table.write('# %s \n' % (system_name)) # legend on file file_table.write('#V(A^3) Etot(eV) \n') #adding wild card to input directory wild_dir = (input_dir + '*/') #creating a list of directories contained in input directory list_dir = glob(wild_dir) for dir in list_dir: if dir != (input_dir + 'PBE_start/'): # reading vasprun.xml and POSCAR with pymatgen poscar = Poscar.from_file(dir + "POSCAR") structure = poscar.structure.as_dict() # getting lattice parameter a = structure['lattice']['a'] # getting volume of cubic cell V = a * a * a # build path of vasprun.xml file path_vasprun = (dir + 'vasprun.xml') # reading VASP OUTPUT vasprun = Vasprun(path_vasprun) etot = vasprun.final_energy file_table.write('%f %f \n' % (V, etot))
def process_killed_run(self, 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.as_dict() d["is_hubbard"] = incar.get("LDAU", False) if d["is_hubbard"]: us = np.array(incar.get("LDAUU", [])) js = np.array(incar.get("LDAUJ", [])) if sum(us - 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.as_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.as_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.as_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": potcar.functional.lower(), "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)).as_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")).as_dict() except: logger.error("Unable to parse OSZICAR for killed " "run in {}.".format(dir_name)) return d
def constrained_opt_run(cls, vasp_cmd, lattice_direction, initial_strain, atom_relax=True, max_steps=20, algo="bfgs", **vasp_job_kwargs): """ Returns a generator of jobs for a constrained optimization run. Typical use case is when you want to approximate a biaxial strain situation, e.g., you apply a defined strain to a and b directions of the lattice, but allows the c-direction to relax. Some guidelines on the use of this method: i. It is recommended you do not use the Auto kpoint generation. The grid generated via Auto may fluctuate with changes in lattice param, resulting in numerical noise. ii. Make sure your EDIFF/EDIFFG is properly set in your INCAR. The optimization relies on these values to determine convergence. Args: vasp_cmd (str): Command to run vasp as a list of args. For example, if you are using mpirun, it can be something like ["mpirun", "pvasp.5.2.11"] lattice_direction (str): Which direction to relax. Valid values are "a", "b" or "c". initial_strain (float): An initial strain to be applied to the lattice_direction. This can usually be estimated as the negative of the strain applied in the other two directions. E.g., if you apply a tensile strain of 0.05 to the a and b directions, you can use -0.05 as a reasonable first guess for initial strain. atom_relax (bool): Whether to relax atomic positions. max_steps (int): The maximum number of runs. Defaults to 20 ( highly unlikely that this limit is ever reached). algo (str): Algorithm to use to find minimum. Default is "bfgs", which is fast, but can be sensitive to numerical noise in energy calculations. The alternative is "bisection", which is more robust but can be a bit slow. The code does fall back on the bisection when bfgs gives a non-sensical result, e.g., negative lattice params. \*\*vasp_job_kwargs: Passthrough kwargs to VaspJob. See :class:`custodian.vasp.jobs.VaspJob`. Returns: Generator of jobs. At the end of the run, an "EOS.txt" is written which provides a quick look at the E vs lattice parameter. """ nsw = 99 if atom_relax else 0 incar = Incar.from_file("INCAR") # Set the energy convergence criteria as the EDIFFG (if present) or # 10 x EDIFF (which itself defaults to 1e-4 if not present). if incar.get("EDIFFG") and incar.get("EDIFFG") > 0: etol = incar["EDIFFG"] else: etol = incar.get("EDIFF", 1e-4) * 10 if lattice_direction == "a": lattice_index = 0 elif lattice_direction == "b": lattice_index = 1 else: lattice_index = 2 energies = {} for i in range(max_steps): if i == 0: settings = [{ "dict": "INCAR", "action": { "_set": { "ISIF": 2, "NSW": nsw } } }] structure = Poscar.from_file("POSCAR").structure x = structure.lattice.abc[lattice_index] backup = True else: backup = False v = Vasprun("vasprun.xml") structure = v.final_structure energy = v.final_energy lattice = structure.lattice x = lattice.abc[lattice_index] energies[x] = energy if i == 1: x *= (1 + initial_strain) else: # Sort the lattice parameter by energies. min_x = min(energies.keys(), key=lambda e: energies[e]) sorted_x = sorted(energies.keys()) ind = sorted_x.index(min_x) if ind == 0: other = ind + 1 elif ind == len(sorted_x) - 1: other = ind - 1 else: other = ind + 1 \ if energies[sorted_x[ind + 1]] \ < energies[sorted_x[ind - 1]] \ else ind - 1 if abs(energies[min_x] - energies[sorted_x[other]]) < etol: logger.info("Stopping optimization! Final %s = %f" % (lattice_direction, min_x)) break if ind == 0 and len(sorted_x) > 2: # Lowest energy lies outside of range of lowest value. # we decrease the lattice parameter in the next # iteration to find a minimum. This applies only when # there are at least 3 values. x = sorted_x[0] - abs(sorted_x[1] - sorted_x[0]) logger.info("Lowest energy lies below bounds. " "Setting %s = %f." % (lattice_direction, x)) elif ind == len(sorted_x) - 1 and len(sorted_x) > 2: # Lowest energy lies outside of range of highest value. # we increase the lattice parameter in the next # iteration to find a minimum. This applies only when # there are at least 3 values. x = sorted_x[-1] + abs(sorted_x[-1] - sorted_x[-2]) logger.info("Lowest energy lies above bounds. " "Setting %s = %f." % (lattice_direction, x)) else: if algo.lower() == "bfgs" and len(sorted_x) >= 4: try: # If there are more than 4 data points, we will # do a quadratic fit to accelerate convergence. x1 = list(energies.keys()) y1 = [energies[j] for j in x1] z1 = np.polyfit(x1, y1, 2) pp = np.poly1d(z1) from scipy.optimize import minimize result = minimize(pp, min_x, bounds=[(sorted_x[0], sorted_x[-1])]) if (not result.success) or result.x[0] < 0: raise ValueError( "Negative lattice constant!") x = result.x[0] logger.info("BFGS minimized %s = %f." % (lattice_direction, x)) except ValueError as ex: # Fall back on bisection algo if the bfgs fails. logger.info(str(ex)) x = (min_x + sorted_x[other]) / 2 logger.info( "Falling back on bisection %s = %f." % (lattice_direction, x)) else: x = (min_x + sorted_x[other]) / 2 logger.info("Bisection %s = %f." % (lattice_direction, x)) lattice = lattice.matrix lattice[lattice_index] = lattice[lattice_index] / \ np.linalg.norm(lattice[lattice_index]) * x s = Structure(lattice, structure.species, structure.frac_coords) fname = "POSCAR.%f" % x s.to(filename=fname) incar_update = {"ISTART": 1, "NSW": nsw, "ISIF": 2} settings = [{ "dict": "INCAR", "action": { "_set": incar_update } }, { "file": fname, "action": { "_file_copy": { "dest": "POSCAR" } } }] logger.info("Generating job = %d with parameter %f!" % (i + 1, x)) yield VaspJob(vasp_cmd, final=False, backup=backup, suffix=".static.%f" % x, settings_override=settings, **vasp_job_kwargs) with open("EOS.txt", "wt") as f: f.write("# %s energy\n" % lattice_direction) for k in sorted(energies.keys()): f.write("%f %f\n" % (k, energies[k]))
def main(): """ logicMain function. Does the cli """ options = docopt(__doc__) poscar_path = options['<poscar>'] if not exists(poscar_path): raise IOError('POSCAR file "{0}" does not exist.'.format(poscar_path)) else: try: structure = Poscar.from_file(poscar_path).structure species = set( map_structure(structure, apply=lambda s: s.specie.symbol)) except: raise IOError( 'Could not parse POSCAR file "{0}"'.format(poscar_path)) if options['--incar']: incar_path = options['--incar'] if not exists(incar_path): raise IOError( 'INCAR file "{0}" does not exist.'.format(incar_path)) else: try: incar = Incar.from_file(incar_path) except: raise IOError( 'Could not parse INCAR file "{0}"'.format(incar_path)) if options['supercell']: try: sx, sy, sz = [int(options['<s{0}>'.format(k)]) for k in 'xyz'] except: raise ValueError('Could not parse supercell parameters') else: structure.make_supercell([sx, sy, sz]) if options['direction']: try: dx, dy, dz = [int(options['<d{0}>'.format(k)]) for k in 'xyz'] except: raise ValueError('Could not parse direction') else: cl_direction = unit_vector(np.array([dx, dy, dz])) else: cl_direction = unit_vector(np.array([1.0, 0.0, 0.0])) lengths = parse_lengths(options['<lengths>']) if not all([k in species for k in lengths.keys()]): missing_elements = set(lengths.keys()) - species raise ValueError( 'The following element{0} {1} not specified in "{2}": {3}'.format( 's' if len(missing_elements) > 1 else '', 'are' if len(missing_elements) > 1 else 'is', poscar_path, ', '.join(list(missing_elements)))) for missing_element in species - set(lengths.keys()): lengths[missing_element] = 0.0 if options['ncl']: magmoms = generate_spins_vecs_ncl(structure, lengths) # Check if net magnetic moment is really zero sum_vec = np.array([array for _, v in magmoms.items() for array in v]) assert np.isclose(np.sum(sum_vec, axis=0), np.zeros((3, ))).all() if options['cl']: if options['--imbalanced']: balanced = False else: balanced = True magmoms = generate_spins_vecs_cl(structure, lengths, direction=cl_direction, balanced=balanced) # Check if net magnetic moment is really zero sum_vec = np.array([array for _, v in magmoms.items() for array in v]) assert np.isclose(np.sum(sum_vec, axis=0), np.zeros((3, ))).all() if options['fm']: magmoms = generate_spins_vecs_fm(structure, lengths, direction=cl_direction) frac_coords_list = [] species_list = [] magmom_str = [] magmoms_site_property = {'magmom': []} for spec, magm in magmoms.items(): # Assemble the species list and the fractional coords in the same order as the generated magnetic moments current_frac_coords = map_structure( structure, predicate=lambda site: site.specie.symbol == spec, apply=lambda site: site.frac_coords) species_list.extend([spec] * len(current_frac_coords)) frac_coords_list.extend(current_frac_coords) # If direction is given calculate the projection of the moment onto the direction which gives length and # orientation if options['direction'] or options['ncl']: magmom_str.extend([ ' '.join([make_format_crumb(i) for i in range(3)]).format(mag_x, mag_y, mag_z) for mag_x, mag_y, mag_z in magm ]) magmoms_site_property['magmom'].extend( [mag_x, mag_y, mag_z] for mag_x, mag_y, mag_z in magm) else: magmom_str.extend([ make_format_crumb(0).format( np.dot(cl_direction, np.array([mag_x, mag_y, mag_z]))) for mag_x, mag_y, mag_z in magm ]) magmoms_site_property['magmom'].extend([ np.dot(cl_direction, np.array([mag_x, mag_y, mag_z])) for mag_x, mag_y, mag_z in magm ]) # Create the new structure new_structure = Structure(structure.lattice, species_list, frac_coords_list, site_properties=magmoms_site_property) magmom_str = ' '.join(magmom_str) # Write the new Posar file Poscar(new_structure).write_file( file_exists('{0}{1}'.format(poscar_path, OUTPUT_SUFFIX))) if options['--incar']: incar['MAGMOM'] = magmom_str incar.write_file(file_exists('INCAR{0}'.format(OUTPUT_SUFFIX))) else: # Print the magnetic moment vector to the terminal print('MAGMOM = {0}'.format(magmom_str)) if options['--plot']: plot_magmoms(magmoms) if options['--cif']: cif_writer = CifWriter(new_structure, write_magmoms=True) cif_writer.write_file( file_exists('{0}{1}.cif'.format(poscar_path, OUTPUT_SUFFIX)))
def run_task(self, fw_spec): from mpmorph.fireworks import powerups from mpmorph.fireworks.core import MDFW # Load Structure from Poscar _poscar = Poscar.from_file("CONTCAR.gz") structure = _poscar.structure # Get convergence parameters from spec converge_params = self["converge_params"] avg_fraction = converge_params.get("avg_fraction", 0.5) convergence_vars = dict(converge_params["converge_type"]) if "ionic" not in convergence_vars.keys(): convergence_vars["ionic"] = 0.0005 rescale_params = self.get("rescale_params", {}) # Load Data from OUTCAR search_keys = [ 'external', 'kinetic energy EKIN', '% ion-electron', 'ETOTAL' ] key_map = { 'density': 'external', 'kinetic energy': 'kinetic energy EKIN', 'ionic': '% ion-electron', 'total energy': 'ETOTAL' } outcar_data = md_data.get_MD_data("./OUTCAR.gz", search_keys=search_keys) # Check for convergence converged = {} _index = search_keys.index(key_map["density"]) _data = np.transpose(outcar_data)[_index].copy() pressure = np.mean(_data[int(avg_fraction * (len(_data) - 1)):]) if "density" in convergence_vars.keys(): if np.abs(pressure) >= convergence_vars["density"]: converged["density"] = False else: converged["density"] = True if "kinetic energy" in convergence_vars.keys(): _index = search_keys.index(key_map["kinetic energy"]) energy = np.transpose(outcar_data)[_index].copy() norm_energy = (energy / structure.num_sites) / np.mean( energy / structure.num_sites) - 1 if np.abs(np.mean(norm_energy[-500:]) - np.mean(norm_energy) ) > convergence_vars["kinetic energy"]: converged["kinetic energy"] = False else: converged["kinetic energy"] = True _index = search_keys.index(key_map["ionic"]) energy = np.transpose(outcar_data)[_index].copy() norm_energies = energy / structure.num_sites mu, std = stats.norm.fit(norm_energies) mu1, std1 = stats.norm.fit(norm_energies[0:int(len(norm_energies) / 2)]) mu2, std2 = stats.norm.fit(norm_energies[int(len(norm_energies) / 2):]) if np.abs((mu2 - mu1) / mu) < convergence_vars["ionic"]: converged["ionic"] = True else: converged["ionic"] = False # Spawn Additional Fireworks if not all([item[1] for item in converged.items()]): density_spawn_count = converge_params["density_spawn_count"] energy_spawn_count = converge_params["energy_spawn_count"] max_rescales = converge_params["max_rescales"] max_energy_runs = 3 # Set max energy convergence runs to default of 3 run_specs = self["run_specs"] md_params = self["md_params"] optional_params = self["optional_fw_params"] tag_id = self.get("tag_id", "") if density_spawn_count >= max_rescales: return FWAction(defuse_children=True) elif energy_spawn_count >= max_energy_runs: # Too many energy rescales... Just continue with the production runs return FWAction(stored_data={ 'pressure': pressure, 'energy': mu, 'density_calculated': True }) elif not converged.get("density", True): rescale_args = { "initial_pressure": pressure * 1000, "initial_temperature": 1, "beta": 0.0000005 } rescale_args = recursive_update(rescale_args, rescale_params) # Spawn fw fw = MDFW( structure, name=f'density_run_{density_spawn_count + 1}-{tag_id}', previous_structure=False, **run_specs, **md_params, **optional_params) converge_params["density_spawn_count"] += 1 _spawner_args = { "converge_params": converge_params, "rescale_params": rescale_params, "run_specs": run_specs, "md_params": md_params, "optional_fw_params": optional_params, "tag_id": tag_id } fw = powerups.add_rescale_volume(fw, **rescale_args) fw = powerups.add_pass_pv(fw) fw = powerups.add_converge_task(fw, **_spawner_args) wf = Workflow([fw]) return FWAction(detours=wf, stored_data={ 'pressure': pressure, 'energy': mu }) else: fw = MDFW(structure, name=f'energy_run_{energy_spawn_count + 1}_{tag_id}', previous_structure=False, **run_specs, **md_params, **optional_params) converge_params["energy_spawn_count"] += 1 _spawner_args = { "converge_params": converge_params, "rescale_params": rescale_params, "run_specs": run_specs, "md_params": md_params, "optional_fw_params": optional_params, "tag_id": tag_id } fw = powerups.add_pass_pv(fw) fw = powerups.add_converge_task(fw, **_spawner_args) wf = Workflow([fw]) return FWAction(detours=wf, stored_data={ 'pressure': pressure, 'energy': mu }) else: return FWAction(stored_data={ 'pressure': pressure, 'energy': mu, 'density_calculated': True })
poscar_out = os.path.join(folder_name, 'POSCAR') poscar_scale(os.path.join(init_path, 'POSCAR'), poscar_out, scale) copyfile(os.path.join(init_path, 'POTCAR'), os.path.join(folder_name, 'POTCAR')) copyfile(os.path.join(init_path, 'INCAR'), os.path.join(folder_name, 'INCAR')) copyfile(os.path.join(init_path, 'KPOINTS'), os.path.join(folder_name, 'KPOINTS')) copyfile(os.path.join(init_path, 'sub_job.sh'), os.path.join(folder_name, 'sub_job.sh')) return folder_name init_path = os.getcwd() poscar_in = os.path.join(init_path, 'POSCAR') structure = Poscar.from_file(poscar_in).structure vol0 = structure.volume existing_runs = glob.glob('r*') existing_vols = [] commands = [] # folders starting from r for folder in existing_runs: if 'POSCAR' in os.listdir(folder): poscar_in_existed = Poscar.from_file(os.path.join(folder, 'POSCAR')) structure = poscar_in_existed.structure vol_existed = structure.volume existing_vols.append(vol_existed) if len(existing_vols) > 0:
def launch_enumlib(count, split): os.mkdir(f'enumlib{count}') os.chdir(f'enumlib{count}') with open('struct_enum.in', 'w') as f: f.write('generated by Automag\n') f.write('bulk\n') for lat_vector in symmetrized_structure.lattice.matrix: for component in lat_vector: f.write(f'{component:14.10f} ') f.write('\n') case = len(split) + sum(split) f.write(f' {case} -nary case\n') f.write( f' {symmetrized_structure.num_sites} # Number of points in the multilattice\n' ) offset = 0 for i, (s, wyckoff) in enumerate( zip(split, symmetrized_structure.equivalent_sites)): if s: offset += 1 for atom in wyckoff: for component in atom.coords: f.write(f'{component:14.10f} ') if s: f.write(f'{i + offset - 1}/{i + offset}\n') else: f.write(f'{i + offset}\n') f.write( f' 1 {supercell_size} # Starting and ending cell sizes for search\n' ) f.write('0.10000000E-06 # Epsilon (finite precision parameter)\n') f.write('full list of labelings\n') f.write('# Concentration restrictions\n') for s, wyckoff in zip(split, symmetrized_structure.equivalent_sites): if s: for _ in range(2): f.write(f'{len(wyckoff):4d}') f.write(f'{len(wyckoff):4d}') f.write(f'{symmetrized_structure.num_sites * 2:4d}\n') else: f.write(f'{len(wyckoff) * 2:4d}') f.write(f'{len(wyckoff) * 2:4d}') f.write(f'{symmetrized_structure.num_sites * 2:4d}\n') process = subprocess.Popen('enum.x') try: process.wait(timeout=60) except subprocess.TimeoutExpired: process.kill() os.system('makeStr.py 1 500') for j in range(501): if os.path.isfile(f'vasp.{j + 1}'): conf_poscar = Poscar.from_file(f'vasp.{j + 1}') else: break if conf_poscar.structure.lattice in lattices: index = lattices.index(conf_poscar.structure.lattice) current_coords = conf_poscar.structure.frac_coords.tolist() reference_coords = coordinates[index].tolist() mapping = [ current_coords.index(coord) for coord in reference_coords ] else: lattices.append(conf_poscar.structure.lattice) coordinates.append(conf_poscar.structure.frac_coords) configurations.append([]) index = len(lattices) - 1 mapping = list(range(len(conf_poscar.structure.frac_coords))) k = 0 groups = [] site_magmoms = [] for s, states in zip(split, wyckoff_magmoms): if s: groups.append([k, k + 1]) for _ in range(2): site_magmoms.append([spin_value, -spin_value]) k += 1 else: site_magmoms.append(states) k += 1 # use a flag to check that all sites which have been split are AFM for conf in product(*site_magmoms): flag = True conf_array = np.array(conf) for group in groups: if sum(conf_array[group]) != 0: flag = False if flag: configuration = np.repeat(conf, conf_poscar.natoms) transformed_configuration = configuration[mapping] if transformed_configuration.tolist() not in configurations[index] and \ [-item for item in transformed_configuration] not in configurations[index]: configurations[index].append( transformed_configuration.tolist()) os.chdir('..')
def setUp(self): struc = PymatgenTest.get_structure("VO2") struc.make_supercell(3) struc = struc self.vac = Vacancy(struc, struc.sites[0], charge=-3) abc = self.vac.bulk_structure.lattice.abc axisdata = [np.arange(0.0, lattval, 0.2) for lattval in abc] bldata = [ np.array([1.0 for u in np.arange(0.0, lattval, 0.2)]) for lattval in abc ] dldata = [ np.array([(-1 - np.cos(2 * np.pi * u / lattval)) for u in np.arange(0.0, lattval, 0.2)]) for lattval in abc ] self.frey_params = { "axis_grid": axisdata, "bulk_planar_averages": bldata, "defect_planar_averages": dldata, "dielectric": 15, "initial_defect_structure": struc.copy(), "defect_frac_sc_coords": struc.sites[0].frac_coords[:], } kumagai_bulk_struc = Poscar.from_file( os.path.join(PymatgenTest.TEST_FILES_DIR, "defect", "CONTCAR_bulk")).structure bulk_out = Outcar( os.path.join(PymatgenTest.TEST_FILES_DIR, "defect", "OUTCAR_bulk.gz")) defect_out = Outcar( os.path.join(PymatgenTest.TEST_FILES_DIR, "defect", "OUTCAR_vac_Ga_-3.gz")) self.kumagai_vac = Vacancy(kumagai_bulk_struc, kumagai_bulk_struc.sites[0], charge=-3) kumagai_defect_structure = self.kumagai_vac.generate_defect_structure() self.kumagai_params = { "bulk_atomic_site_averages": bulk_out.electrostatic_potential, "defect_atomic_site_averages": defect_out.electrostatic_potential, "site_matching_indices": [[ind, ind - 1] for ind in range(len(kumagai_bulk_struc))], "defect_frac_sc_coords": [0.0, 0.0, 0.0], "initial_defect_structure": kumagai_defect_structure, "dielectric": 18.118 * np.identity(3), "gamma": 0.153156, # not neccessary to load gamma, but speeds up unit test } v = Vasprun(os.path.join(PymatgenTest.TEST_FILES_DIR, "vasprun.xml")) eigenvalues = v.eigenvalues.copy() kptweights = v.actual_kpoints_weights potalign = -0.1 vbm = v.eigenvalue_band_properties[2] cbm = v.eigenvalue_band_properties[1] self.bandfill_params = { "eigenvalues": eigenvalues, "kpoint_weights": kptweights, "potalign": potalign, "vbm": vbm, "cbm": cbm, } self.band_edge_params = { "hybrid_cbm": 1.0, "hybrid_vbm": -1.0, "vbm": -0.5, "cbm": 0.6, "num_hole_vbm": 1.0, "num_elec_cbm": 1.0, }
def test_run_neb_subfolders(self): #raise SkipTest ingdir = "%s/writedir/neb_labelinit-labelfin_stat" % testdir recipedir = "%s/writedir" % testdir topmetad = MASTFile("files/top_metadata_neb") topmetad.data.append("origin_dir = %s/files\n" % testdir) #give origin directory topmetad.to_file("writedir/metadata.txt") metad = MASTFile("files/metadata_neb") metad.to_file("%s/metadata.txt" % ingdir) kdict = dict() kdict['mast_program'] = 'vasp' kdict['mast_kpoints'] = [2, 2, 2, "M"] kdict['mast_xc'] = 'pw91' neblines = list() neblines.append(["Cr", "0.0 0.9 0.8", "0.0 0.8 0.7"]) neblines.append(["Cr", "0.4 0.2 0.1", "0.3 0.3 0.2"]) neblines.append(["Cr", "0.29 0.05 0.05", "0.01 0.01 0.98"]) neblines.append(["Ni", "0.61 0.99 0.98", "0.25 0.01 0.97"]) kdict['mast_neb_settings'] = dict() kdict['mast_neb_settings']['lines'] = neblines kdict['mast_neb_settings']['images'] = 3 str_00 = MASTFile("files/POSCAR_00") str_00.to_file("%s/parent_structure_labelinit" % ingdir) str_04 = MASTFile("files/POSCAR_04") str_04.to_file("%s/parent_structure_labelfin" % ingdir) str_01 = MASTFile("files/POSCAR_01") str_01.to_file("%s/parent_structure_labelinit-labelfin_01" % ingdir) str_02 = MASTFile("files/POSCAR_02") str_02.to_file("%s/parent_structure_labelinit-labelfin_02" % ingdir) str_03 = MASTFile("files/POSCAR_03") str_03.to_file("%s/parent_structure_labelinit-labelfin_03" % ingdir) en_00 = MASTFile("files/OSZICAR_00") en_00.to_file("%s/parent_energy_labelinit" % ingdir) en_04 = MASTFile("files/OSZICAR_04") en_04.to_file("%s/parent_energy_labelfin" % ingdir) my_structure = Poscar.from_file("files/perfect_structure").structure mywr = ChopIngredient(name=ingdir, program_keys=kdict, structure=my_structure) mywr.write_neb_subfolders() myri = ChopIngredient(name=ingdir, program_keys=kdict, structure=my_structure) myri.run_neb_subfolders() mysubmit = MASTFile("%s/submitlist" % self.test_control) myri.checker.keywords['name'] = "%s/00" % ingdir self.assertFalse( myri.checker.is_ready_to_run()) #do not run endpoints again myri.checker.keywords['name'] = "%s/01" % ingdir self.assertTrue(myri.checker.is_ready_to_run()) myri.checker.keywords['name'] = "%s/02" % ingdir self.assertTrue(myri.checker.is_ready_to_run()) myri.checker.keywords['name'] = "%s/03" % ingdir self.assertTrue(myri.checker.is_ready_to_run()) myri.checker.keywords['name'] = "%s/04" % ingdir self.assertFalse( myri.checker.is_ready_to_run()) #do not run endpoints again self.assertEquals(mysubmit.data[0], "%s/01\n" % ingdir) self.assertEquals(mysubmit.data[1], "%s/02\n" % ingdir) self.assertEquals(mysubmit.data[2], "%s/03\n" % ingdir)
def bs_graph(rawdatadir, savedir, e_fermi, soc=False): run = BSVasprun("{}/vasprun.xml".format(rawdatadir), parse_projected_eigen=True) bs = run.get_band_structure(efermi=e_fermi, line_mode=True, force_hybrid_mode=True) bsplot = BSPlotter(bs) # Get the plot bsplot.get_plot(vbm_cbm_marker=True, ylim=(-1.5, 1.5), zero_to_efermi=True) bs_graph.e_fermi = float(bs.efermi) bs_graph.band_gap = float(bs.get_band_gap()["energy"]) ax = plt.gca() xlim = ax.get_xlim() ylim = ax.get_ylim() ax.hlines(0, xlim[0], xlim[1], linestyle="--", color="black") ax.tick_params(labelsize=20) if not soc: ax.plot((), (), "r-", label="spin up") ax.plot((), (), "b-", label="spin down") ax.legend(fontsize=16, loc="upper left") plt.savefig("{}/BSGraph".format(savedir)) plt.close() if not soc: # Print quick info about band gap (source: vasprun.xml) #print(bs_graph.e_fermi) #print(bs_graph.band_gap) # Get quick info about band gap (source: EIGENVAL) eigenval = Eigenval("{}/EIGENVAL".format(rawdatadir)) bs_graph.band_properties = eigenval.eigenvalue_band_properties # Get detailed info about band gap and CB/VB in each spin channel # (source: EIGENVAL) bs_graph.eigenvalues = eigenval.eigenvalues bs_graph.kpoints = eigenval.kpoints poscar = Poscar.from_file("{}/POSCAR".format(rawdatadir)) bs_graph.lattice = poscar.structure.lattice.reciprocal_lattice bs_graph.eigenvalues[Spin.up] = bs_graph.eigenvalues[ Spin.up][:, :, :-1] bs_graph.eigenvalues[Spin.down] = bs_graph.eigenvalues[ Spin.down][:, :, :-1] bs_graph.eigenvalues[Spin.up] = bs_graph.eigenvalues[Spin.up][:, :, 0] bs_graph.eigenvalues[Spin.down] = bs_graph.eigenvalues[Spin.down][:, :, 0] bs_graph.eigenvalues[Spin.up] = \ np.transpose(bs_graph.eigenvalues[Spin.up]) bs_graph.eigenvalues[Spin.down] = \ np.transpose(bs_graph.eigenvalues[Spin.down]) bs = BandStructure(bs_graph.kpoints, bs_graph.eigenvalues, bs_graph.lattice, bs_graph.e_fermi) bs_graph.vbm = bs.get_vbm()["energy"] bs_graph.cbm = bs.get_cbm()["energy"] bs_graph.electronic_gap = bs.get_band_gap()["energy"] bs_graph.direct = bs.get_band_gap()["direct"] if bs_graph.vbm and bs_graph.cbm and bs_graph.electronic_gap: bs_graph.gap_by_spin = bs.get_direct_band_gap_dict() return
def test_run_scale_defect(self): #raise SkipTest ingdir = "%s/writedir/single_label1" % testdir recipedir = "%s/writedir" % testdir topmetad = MASTFile("files/top_metadata_single") topmetad.data.append("origin_dir = %s/files\n" % testdir) #give origin directory topmetad.to_file("writedir/metadata.txt") metad = MASTFile("files/metadata_single") metad.data.append("defect_label = label1\n") metad.data.append("scaling_size = [2,2,2]\n") metad.to_file("%s/metadata.txt" % ingdir) kdict = dict() kdict['label1'] = dict() kdict['label1']['subdefect1'] = dict() kdict['label1']['subdefect1']['symbol'] = 'Cr' kdict['label1']['subdefect1']['type'] = 'interstitial' kdict['label1']['subdefect1']['coordinates'] = np.array( [0.8, 0.7, 0.6]) kdict['label1']['subdefect2'] = dict() kdict['label1']['subdefect2']['symbol'] = 'Sr' kdict['label1']['subdefect2']['type'] = 'antisite' kdict['label1']['subdefect2']['coordinates'] = np.array( [0.5, 0.5, 0.0]) kdict['label1']['subdefect3'] = dict() kdict['label1']['subdefect3']['symbol'] = 'Cr' kdict['label1']['subdefect3']['type'] = 'interstitial' kdict['label1']['subdefect3']['coordinates'] = np.array( [0.3, 0.3, 0.2]) kdict['label1']['subdefect4'] = dict() kdict['label1']['subdefect4']['symbol'] = 'Fe' kdict['label1']['subdefect4']['type'] = 'substitution' kdict['label1']['subdefect4']['coordinates'] = np.array( [0.25, 0.75, 0.75]) kdict['label1']['subdefect5'] = dict() kdict['label1']['subdefect5']['symbol'] = 'O' kdict['label1']['subdefect5']['type'] = 'vacancy' kdict['label1']['subdefect5']['coordinates'] = np.array( [0.5, 0.25, 0.75]) kdict['label1']['subdefect6'] = dict() kdict['label1']['subdefect6']['symbol'] = 'Fe' kdict['label1']['subdefect6']['type'] = 'substitution' kdict['label1']['subdefect6']['coordinates'] = np.array( [0.25, 0.25, 0.25]) kdict['label1']['subdefect7'] = dict() kdict['label1']['subdefect7']['symbol'] = 'La' kdict['label1']['subdefect7']['type'] = 'vacancy' kdict['label1']['subdefect7']['coordinates'] = np.array([0, 0, 0.5]) kdict['label1']['subdefect8'] = dict() kdict['label1']['subdefect8']['symbol'] = 'Ni' kdict['label1']['subdefect8']['type'] = 'interstitial' kdict['label1']['subdefect8']['coordinates'] = np.array( [0.4, 0.1, 0.3]) kdict['label1']['coord_type'] = 'fractional' kdict['label1']['threshold'] = 0.01 kdict['label1']['charge'] = '2' mdict = dict() mdict['mast_program'] = 'vasp' mdict['mast_defect_settings'] = dict() mdict['mast_defect_settings'].update(kdict['label1']) my_structure = Poscar.from_file("files/POSCAR_perfect").structure myperf = MASTFile("files/POSCAR_perfect") myperf.to_file("%s/POSCAR" % ingdir) myri = ChopIngredient(name=ingdir, program_keys=mdict, structure=my_structure) myri.run_scale() #copy contcar to poscar os.rename("%s/CONTCAR" % ingdir, "%s/POSCAR" % ingdir) myri.run_defect() my_defected = Poscar.from_file( "%s/CONTCAR" % ingdir).structure.get_sorted_structure() defected_compare = Poscar.from_file( "files/POSCAR_scaled_defected").structure.get_sorted_structure() self.assertEquals(my_defected, defected_compare)
list_dir = glob(wild_dir) # search in every directory of the list for dir in list_dir: path = os.path.dirname(dir) # identifying last folder of path subfold = os.path.basename(path) # finding charge state from subfolder name HF_par = subfold.replace('HF_', '') HF = float(HF_par) # build path of OUTCAR file path_vasprun = (dir + 'vasprun.xml') # reading vasprun.xml and CONTCAR with pymatgen contcar = Poscar.from_file(dir + "CONTCAR") structure = contcar.structure.as_dict() # getting lattice parameter lattice_par = structure['lattice']['a'] # reading VASP OUTPUT vasprun = Vasprun(path_vasprun) #getting energy gap (gap, cbm, vbm, is_direct) = vasprun.eigenvalue_band_properties # writing output file with charge state and total enery file_table.write('%f %f %f \n' % (HF, lattice_par, gap)) file_table.close() print(f'Data printed in "{system_name}-a-Eg.dat"') print('')
import pymatgen as mg from pymatgen.io.vasp import Poscar from pymatgen.io.cif import CifWriter import os if os.path.isfile( 'files.txt' ): # For a list of folder names with POSCARs inside them, will write their symmetrized versions with open('files.txt') as f: cwd = os.getcwd() for line in f.readlines(): path = cwd + '/' + line.split()[0] os.chdir(path) p = Poscar.from_file('POSCAR') z = CifWriter(p.structure, symprec=0.001) z.write_file(cwd + '/pymat_cifs/' + '%s_pymat.cif' % line.split()[0]) elif os.path.isfile( 'cif_files.txt' ): # For a list of cif filenames, will write their symmetrized versions with open('cif_files.txt') as f: for line in f.readlines(): path = line.split()[0] os.mkdir("./pymat_cifs") struct = mg.Structure.from_file(path) z = CifWriter(struct, symprec=0.001) z.write_file('./pymat_cifs/' + '%s_pymat.cif' % path.split(".")[0]) else: # If you just want the symmetrized cif for one POSCAR p = Poscar.from_file('POSCAR')
def test_kumagai(self): gamma = 0.19357221 prec = 28 lattice = Lattice([[4.692882, -8.12831, 0.], [4.692882, 8.12831, 0.], [0., 0., 10.03391]]) #note that real/recip vector generation is not dependent on epsilon g_vecs, _, r_vecs, _ = generate_R_and_G_vecs(gamma, prec, lattice, 80. * np.identity(3)) #test real space summation (bigger for large epsilon) kc_high_diel = KumagaiCorrection(80. * np.identity(3), gamma=gamma) real_sum = kc_high_diel.get_real_summation(gamma, r_vecs[0]) self.assertAlmostEqual(real_sum, 0.00843104) #test recip space summation (bigger for small epsilon) kc_low_diel = KumagaiCorrection(0.1 * np.identity(3), gamma=gamma) recip_sum = kc_low_diel.get_recip_summation(gamma, g_vecs[0], lattice.volume) self.assertAlmostEqual(recip_sum, 0.31117099) #test self interaction si_corr = kc_low_diel.get_self_interaction(gamma) self.assertAlmostEqual(si_corr, -0.54965249) #test potenital shift interaction correction ps_corr = kc_low_diel.get_potential_shift(gamma, lattice.volume) self.assertAlmostEqual(ps_corr, -0.00871593) # """Test Defect Entry approach to correction """ bulk_struc = Poscar.from_file( os.path.join(test_dir, 'defect', 'CONTCAR_bulk')).structure bulk_out = Outcar(os.path.join(test_dir, 'defect', 'OUTCAR_bulk.gz')) defect_out = Outcar( os.path.join(test_dir, 'defect', 'OUTCAR_vac_Ga_-3.gz')) epsilon = 18.118 * np.identity(3) vac = Vacancy(bulk_struc, bulk_struc.sites[0], charge=-3) defect_structure = vac.generate_defect_structure() defect_frac_coords = [0., 0., 0.] parameters = { 'bulk_atomic_site_averages': bulk_out.electrostatic_potential, 'defect_atomic_site_averages': defect_out.electrostatic_potential, 'site_matching_indices': [[ind, ind - 1] for ind in range(len(bulk_struc))], 'initial_defect_structure': defect_structure, 'defect_frac_sc_coords': defect_frac_coords } dentry = DefectEntry(vac, 0., parameters=parameters) kc = KumagaiCorrection(epsilon) kcorr = kc.get_correction(dentry) self.assertAlmostEqual(kcorr['kumagai_electrostatic'], 0.88236299) self.assertAlmostEqual(kcorr['kumagai_potential_alignment'], 2.09704862) # test ES correction high_diel_es_corr = kc_high_diel.perform_es_corr( gamma, prec, lattice, -3.) self.assertAlmostEqual(high_diel_es_corr, 0.25176240) low_diel_es_corr = kc_low_diel.perform_es_corr(gamma, prec, lattice, -3.) self.assertAlmostEqual(low_diel_es_corr, 201.28810966) # test pot correction site_list = [] for bs_ind, ds_ind in dentry.parameters['site_matching_indices']: Vqb = -(defect_out.electrostatic_potential[ds_ind] - bulk_out.electrostatic_potential[bs_ind]) site_list.append([defect_structure[ds_ind], Vqb]) sampling_radius = dentry.parameters["kumagai_meta"]["sampling_radius"] gamma = dentry.parameters["kumagai_meta"]["gamma"] q = -3 g_vecs, _, r_vecs, _ = generate_R_and_G_vecs(gamma, 28, defect_structure.lattice, np.identity(3)) high_diel_pot_corr = kc_high_diel.perform_pot_corr( defect_structure, defect_frac_coords, site_list, sampling_radius, q, r_vecs[0], g_vecs[0], gamma) self.assertAlmostEqual(high_diel_pot_corr, 2.35840716) low_diel_pot_corr = kc_low_diel.perform_pot_corr( defect_structure, defect_frac_coords, site_list, sampling_radius, q, r_vecs[0], g_vecs[0], gamma) self.assertAlmostEqual(low_diel_pot_corr, -58.83598095) #test the kumagai plotter kcp = kc.plot() self.assertTrue(kcp) #check that uncertainty metadata exists self.assertAlmostEqual( set(kc.metadata['pot_corr_uncertainty_md'].keys()), set(['number_sampled', 'stats']))
from pymatgen.io.vasp import Poscar # from pymatgen import * # from numpy import pi # from numpy import arccos, dot # pi # from numpy.linalg import norm # import numpy as np yourfile = input('Choose a file: ') p = Poscar.from_file(yourfile) coordi = p.structure.frac_coords[:] print(coordi) # lattice_vector_R = p.structure.lattice.matrix # print(lattice_vector_R)
from pymatgen import Structure, Lattice import numpy as np import operator from site_analysis import Atom, Analysis, ShortestDistanceSite, get_vertex_indices, AtomsTrajectory, SitesTrajectory from collections import Counter import tqdm x1 = Xdatcar('1/XDATCAR') x2 = Xdatcar('2/XDATCAR') x3 = Xdatcar('3/XDATCAR') x4 = Xdatcar('4/XDATCAR') x5 = Xdatcar('5/XDATCAR') structures = x1.structures + x2.structures + x3.structures + x4.structures + x5.structures all_na_structure = Poscar.from_file('na_sn_all_na_ext.POSCAR.vasp').structure vertex_species = 'S' centre_species = 'Na' sg = SpaceGroup('I41/acd:2') from pymatgen import Structure, Lattice lattice = all_na_structure.lattice na1 = Structure.from_spacegroup(sg='I41/acd:2', lattice=lattice, species=['Na'], coords=[[0.25, 0.0, 0.125]]) na2 = Structure.from_spacegroup(sg='I41/acd:2', lattice=lattice, species=['Na'], coords=[[0.00, 0.0, 0.125]]) na3 = Structure.from_spacegroup(sg='I41/acd:2', lattice=lattice, species=['Na'], coords=[[0.0, 0.25, 0.0]]) na4 = Structure.from_spacegroup(sg='I41/acd:2', lattice=lattice, species=['Na'], coords=[[0.0, 0.0, 0.0]]) na5 = Structure.from_spacegroup(sg='I41/acd:2', lattice=lattice, species=['Na'], coords=[[0.75, 0.25, 0.0]]) na6 = Structure.from_spacegroup(sg='I41/acd:2', lattice=lattice, species=['Na'], coords=[[0.5, 0.75, 0.625]]) i2 = Structure.from_spacegroup(sg='I41/acd:2', lattice=lattice, species=['Na'], coords=[[0.666, 0.1376, 0.05]]) na_structures = {'Na1': na1, 'Na2': na2,
def test_run_defect(self): #raise SkipTest ingdir = "%s/writedir/single_label1" % testdir recipedir = "%s/writedir" % testdir topmetad = MASTFile("files/top_metadata_single") topmetad.data.append("origin_dir = %s/files\n" % testdir) #give origin directory topmetad.to_file("writedir/metadata.txt") metad = MASTFile("files/metadata_single") metad.data.append("defect_label = label1\n") metad.data.append("scaling_size = [1,1,1]\n") metad.to_file("%s/metadata.txt" % ingdir) kdict = dict() kdict['label1'] = dict() kdict['label1']['subdefect1'] = dict() kdict['label1']['subdefect1']['symbol'] = 'Cr' kdict['label1']['subdefect1']['type'] = 'interstitial' kdict['label1']['subdefect1']['coordinates'] = np.array( [0.8, 0.7, 0.6]) kdict['label1']['subdefect2'] = dict() kdict['label1']['subdefect2']['symbol'] = 'Sr' kdict['label1']['subdefect2']['type'] = 'antisite' kdict['label1']['subdefect2']['coordinates'] = np.array( [0.5, 0.5, 0.0]) kdict['label1']['subdefect3'] = dict() kdict['label1']['subdefect3']['symbol'] = 'Cr' kdict['label1']['subdefect3']['type'] = 'interstitial' kdict['label1']['subdefect3']['coordinates'] = np.array( [0.3, 0.3, 0.2]) kdict['label1']['subdefect4'] = dict() kdict['label1']['subdefect4']['symbol'] = 'Fe' kdict['label1']['subdefect4']['type'] = 'substitution' kdict['label1']['subdefect4']['coordinates'] = np.array( [0.25, 0.75, 0.75]) kdict['label1']['subdefect5'] = dict() kdict['label1']['subdefect5']['symbol'] = 'O' kdict['label1']['subdefect5']['type'] = 'vacancy' kdict['label1']['subdefect5']['coordinates'] = np.array( [0.5, 0.25, 0.75]) kdict['label1']['subdefect6'] = dict() kdict['label1']['subdefect6']['symbol'] = 'Fe' kdict['label1']['subdefect6']['type'] = 'substitution' kdict['label1']['subdefect6']['coordinates'] = np.array( [0.25, 0.25, 0.25]) kdict['label1']['subdefect7'] = dict() kdict['label1']['subdefect7']['symbol'] = 'La' kdict['label1']['subdefect7']['type'] = 'vacancy' kdict['label1']['subdefect7']['coordinates'] = np.array([0, 0, 0.5]) kdict['label1']['subdefect8'] = dict() kdict['label1']['subdefect8']['symbol'] = 'Ni' kdict['label1']['subdefect8']['type'] = 'interstitial' kdict['label1']['subdefect8']['coordinates'] = np.array( [0.4, 0.1, 0.3]) kdict['label1']['coord_type'] = 'fractional' kdict['label1']['threshold'] = 0.01 kdict['label1']['charge'] = '2' ddict = dict() ddict['mast_defect_settings'] = dict() ddict['mast_defect_settings'].update( kdict['label1']) #single defect grouping ddict['mast_program'] = 'vasp' my_structure = Poscar.from_file("files/POSCAR_perfect").structure myperf = MASTFile("files/POSCAR_perfect") myperf.to_file("%s/POSCAR" % ingdir) myri = ChopIngredient(name=ingdir, program_keys=ddict, structure=my_structure) myri.run_defect() # #defect = kdict['label1'] #base_structure = my_structure.copy() #from MAST.ingredients.pmgextend.structure_extensions import StructureExtensions #for key in defect: # if 'subdefect' in key: # subdefect = defect[key] # sxtend = StructureExtensions(struc_work1=base_structure) # base_structure = sxtend.induce_defect(subdefect, defect['coord_type'], defect['threshold']) # print base_structure # else: # pass #return # # my_defected = Poscar.from_file( "%s/CONTCAR" % ingdir).structure.get_sorted_structure() defected_compare = Poscar.from_file( "files/POSCAR_multi").structure.get_sorted_structure() self.assertEquals(my_defected, defected_compare) self.assertFalse(os.path.isfile("%s/submitlist" % self.test_control))
def UBER_FUNC(d, E_0, l, d_0): return -E_0 * (1 + (d - d_0) / l) * np.exp(-(d - d_0) / l) if __name__ == '__main__': d, E = [], [] Module_Number = 6 Situation_Number = 1 start_number = 1 finish_number = 24 UBER_file = open( "/mnt/c/Users/jackx/OneDrive/Calculation_Data/TC17_TI80/UBER_Results/M{0}_S{1}" .format(Module_Number, Situation_Number), 'r') original_poscar = Poscar.from_file( "/mnt/c/Users/jackx/OneDrive/Calculation_Data/TC17_TI80/Initial_Structures/POSCAR_M{0}_S{1}" .format(int(Module_Number), int(Situation_Number))) lines = UBER_file.readlines() for number_data in range(0, lines.__len__(), 4): d.append(float(lines[number_data + 1].strip("DISTANCE="))) E.append(float(lines[number_data + 3].strip("W_seq="))) E = np.array(E) d = np.array(d) Area_Value = original_poscar.structure.lattice.a * original_poscar.structure.lattice.b * sin( original_poscar.structure.lattice.alpha * pi / 180) eV2J = 16.0217662 parameter, func = curve_fit( lambda d, E_0, l, d_0: UBER_FUNC(d, E_0, l, d_0), d[start_number:finish_number], E[start_number:finish_number])
def full_opt_run(cls, vasp_cmd, vol_change_tol=0.02, max_steps=10, ediffg=-0.05, half_kpts_first_relax=False, **vasp_job_kwargs): """ Returns a generator of jobs for a full optimization run. Basically, this runs an infinite series of geometry optimization jobs until the % vol change in a particular optimization is less than vol_change_tol. Args: vasp_cmd (str): Command to run vasp as a list of args. For example, if you are using mpirun, it can be something like ["mpirun", "pvasp.5.2.11"] vol_change_tol (float): The tolerance at which to stop a run. Defaults to 0.05, i.e., 5%. max_steps (int): The maximum number of runs. Defaults to 10 ( highly unlikely that this limit is ever reached). ediffg (float): Force convergence criteria for subsequent runs ( ignored for the initial run.) half_kpts_first_relax (bool): Whether to halve the kpoint grid for the first relaxation. Speeds up difficult convergence considerably. Defaults to False. \*\*vasp_job_kwargs: Passthrough kwargs to VaspJob. See :class:`custodian.vasp.jobs.VaspJob`. Returns: Generator of jobs. """ for i in range(max_steps): if i == 0: settings = None backup = True if half_kpts_first_relax and os.path.exists("KPOINTS") and \ os.path.exists("POSCAR"): kpts = Kpoints.from_file("KPOINTS") orig_kpts_dict = kpts.as_dict() kpts.kpts = np.maximum(np.array(kpts.kpts) / 2, 1).tolist() low_kpts_dict = kpts.as_dict() settings = [ {"dict": "KPOINTS", "action": {"_set": low_kpts_dict}} ] else: backup = False initial = Poscar.from_file("POSCAR").structure final = Poscar.from_file("CONTCAR").structure vol_change = (final.volume - initial.volume) / initial.volume logger.info("Vol change = %.1f %%!" % (vol_change * 100)) if abs(vol_change) < vol_change_tol: logger.info("Stopping optimization!") break else: incar_update = {"ISTART": 1} if ediffg: incar_update["EDIFFG"] = ediffg settings = [ {"dict": "INCAR", "action": {"_set": incar_update}}, {"file": "CONTCAR", "action": {"_file_copy": {"dest": "POSCAR"}}}] if i == 1 and half_kpts_first_relax: settings.append({"dict": "KPOINTS", "action": {"_set": orig_kpts_dict}}) logger.info("Generating job = %d!" % (i+1)) yield VaspJob(vasp_cmd, final=False, backup=backup, suffix=".relax%d" % (i+1), settings_override=settings, **vasp_job_kwargs)
return 0 #read symmetry information ''' poscar = Poscar.from_file("CONTCAR") structure = poscar.structure Symmetry=SpacegroupAnalyzer(structure, symprec=0.01, angle_tolerance=5) symmops=Symmetry.get_symmetry_operations(cartesian=True) ''' nli = 0 for i in range(7737): if not os.path.isfile("select/%d" % (i)): continue poscar = Poscar.from_file("select/%d" % (i)) structure = poscar.structure Symmetry = SpacegroupAnalyzer(structure, symprec=0.01, angle_tolerance=5) symmops = Symmetry.get_symmetry_operations(cartesian=True) f = open('poscar/POSCAR_%d' % (i), 'r') #read lattice information title = f.readline().strip() scale = f.readline() scale = float(scale) a = f.readline().split() b = f.readline().split() c = f.readline().split() a = [float(j) for j in a] b = [float(j) for j in b] c = [float(j) for j in c] #read atom labels and number of atoms
def readpos(struct_file): if os.path.exists(struct_file): p = Poscar.from_file(struct_file) return (p)
def from_dir(cls, root_dir, relaxation_dirs=None, **kwargs): """ Initializes a NEBAnalysis object from a directory of a NEB run. Note that OUTCARs must be present in all image directories. For the terminal OUTCARs from relaxation calculations, you can specify the locations using relaxation_dir. If these are not specified, the code will attempt to look for the OUTCARs in 00 and 0n directories, followed by subdirs "start", "end" or "initial", "final" in the root_dir. These are just some typical conventions used preferentially in Shyue Ping's MAVRL research group. For the non-terminal points, the CONTCAR is read to obtain structures. For terminal points, the POSCAR is used. The image directories are assumed to be the only directories that can be resolved to integers. E.g., "00", "01", "02", "03", "04", "05", "06". The minimum sub-directory structure that can be parsed is of the following form ( a 5-image example is shown): 00: - POSCAR - OUTCAR 01, 02, 03, 04, 05: - CONTCAR - OUTCAR 06: - POSCAR - OUTCAR Args: root_dir (str): Path to the root directory of the NEB calculation. relaxation_dirs (tuple): This specifies the starting and ending relaxation directories from which the OUTCARs are read for the terminal points for the energies. Returns: NEBAnalysis object. """ neb_dirs = [] for d in os.listdir(root_dir): pth = os.path.join(root_dir, d) if os.path.isdir(pth) and d.isdigit(): i = int(d) neb_dirs.append((i, pth)) neb_dirs = sorted(neb_dirs, key=lambda d: d[0]) outcars = [] structures = [] # Setup the search sequence for the OUTCARs for the terminal # directories. terminal_dirs = [] if relaxation_dirs is not None: terminal_dirs.append(relaxation_dirs) terminal_dirs.append((neb_dirs[0][1], neb_dirs[-1][1])) terminal_dirs.append( [os.path.join(root_dir, d) for d in ["start", "end"]]) terminal_dirs.append( [os.path.join(root_dir, d) for d in ["initial", "final"]]) for i, d in neb_dirs: outcar = glob.glob(os.path.join(d, "OUTCAR*")) contcar = glob.glob(os.path.join(d, "CONTCAR*")) poscar = glob.glob(os.path.join(d, "POSCAR*")) terminal = i == 0 or i == neb_dirs[-1][0] if terminal: found = False for ds in terminal_dirs: od = ds[0] if i == 0 else ds[1] outcar = glob.glob(os.path.join(od, "OUTCAR*")) if outcar: outcar = sorted(outcar) outcars.append(Outcar(outcar[-1])) found = True break if not found: raise ValueError("OUTCAR cannot be found for terminal " "point %s" % d) structures.append(Poscar.from_file(poscar[0]).structure) else: outcars.append(Outcar(outcar[0])) structures.append(Poscar.from_file(contcar[0]).structure) return NEBAnalysis.from_outcars(outcars, structures, **kwargs)
def setUp(self): struc = PymatgenTest.get_structure("VO2") struc.make_supercell(3) struc = struc self.vac = Vacancy(struc, struc.sites[0], charge=-3) abc = self.vac.bulk_structure.lattice.abc axisdata = [np.arange(0., lattval, 0.2) for lattval in abc] bldata = [ np.array([1. for u in np.arange(0., lattval, 0.2)]) for lattval in abc ] dldata = [ np.array([(-1 - np.cos(2 * np.pi * u / lattval)) for u in np.arange(0., lattval, 0.2)]) for lattval in abc ] self.frey_params = { 'axis_grid': axisdata, 'bulk_planar_averages': bldata, 'defect_planar_averages': dldata, 'dielectric': 15, 'initial_defect_structure': struc.copy(), 'defect_frac_sc_coords': struc.sites[0].frac_coords[:] } kumagai_bulk_struc = Poscar.from_file( os.path.join(test_dir, 'defect', 'CONTCAR_bulk')).structure bulk_out = Outcar(os.path.join(test_dir, 'defect', 'OUTCAR_bulk.gz')) defect_out = Outcar( os.path.join(test_dir, 'defect', 'OUTCAR_vac_Ga_-3.gz')) self.kumagai_vac = Vacancy(kumagai_bulk_struc, kumagai_bulk_struc.sites[0], charge=-3) kumagai_defect_structure = self.kumagai_vac.generate_defect_structure() self.kumagai_params = { 'bulk_atomic_site_averages': bulk_out.electrostatic_potential, 'defect_atomic_site_averages': defect_out.electrostatic_potential, 'site_matching_indices': [[ind, ind - 1] for ind in range(len(kumagai_bulk_struc))], 'defect_frac_sc_coords': [0., 0., 0.], 'initial_defect_structure': kumagai_defect_structure, 'dielectric': 18.118 * np.identity(3), 'gamma': 0.153156 # not neccessary to load gamma, but speeds up unit test } v = Vasprun(os.path.join(test_dir, 'vasprun.xml')) eigenvalues = v.eigenvalues.copy() kptweights = v.actual_kpoints_weights potalign = -0.1 vbm = v.eigenvalue_band_properties[2] cbm = v.eigenvalue_band_properties[1] self.bandfill_params = { 'eigenvalues': eigenvalues, 'kpoint_weights': kptweights, 'potalign': potalign, 'vbm': vbm, 'cbm': cbm } self.band_edge_params = { 'hybrid_cbm': 1., 'hybrid_vbm': -1., 'vbm': -0.5, 'cbm': 0.6, 'num_hole_vbm': 1., 'num_elec_cbm': 1. }
def main( structure, shear_strain_ratio, twinmode, twintype, xshift, yshift, dim, layers, delta, expansion_ratios, no_make_tb_flat, posfile, get_poscar, get_lattice, output, is_primitive, get_primitive_standardized, get_conventional_standardized, dump, show_nearest_distance, ): move_atoms_into_unitcell = True symprec = 1e-5 no_idealize = False no_sort = True get_sort_list = False if posfile is None: print("Warning:") print(" POSCAR file did not specify") print(" Set automatically, a=2.93, c=4.65, symbol='Ti', " "wyckoff='c'") lattice = get_hexagonal_lattice_from_a_c(a=2.93, c=4.65) symbol = 'Ti' wyckoff = 'c' else: poscar = Poscar.from_file(posfile) pmgstructure = poscar.structure cell = get_cell_from_pymatgen_structure(pmgstructure) lattice = cell[0] symbol = cell[2][0] wyckoff = get_wyckoff_from_hcp(cell) twinpy = Twinpy(lattice=lattice, twinmode=twinmode, symbol=symbol, wyckoff=wyckoff) if get_poscar: if output is None: output = _get_output_name(structure=structure, get_lattice=get_lattice, shear_strain_ratio=shear_strain_ratio, twinmode=twinmode) if structure == 'shear': twinpy.set_shear(xshift=xshift, yshift=yshift, dim=dim, shear_strain_ratio=shear_strain_ratio, expansion_ratios=expansion_ratios, is_primitive=is_primitive) std = twinpy.get_shear_standardize( get_lattice=get_lattice, move_atoms_into_unitcell=move_atoms_into_unitcell, ) else: make_tb_flat = not no_make_tb_flat twinpy.set_twinboundary(twintype=twintype, xshift=xshift, yshift=yshift, layers=layers, delta=delta, shear_strain_ratio=shear_strain_ratio, expansion_ratios=expansion_ratios, make_tb_flat=make_tb_flat) std = twinpy.get_twinboundary_standardize( get_lattice=get_lattice, move_atoms_into_unitcell=move_atoms_into_unitcell, ) if show_nearest_distance: from twinpy.structure.twinboundary \ import plot_nearest_atomic_distance_of_twinboundary plot_nearest_atomic_distance_of_twinboundary( lattice=lattice, symbol=symbol, twinmode=twinmode, layers=layers, wyckoff=wyckoff, delta=delta, twintype=twintype, shear_strain_ratio=shear_strain_ratio, expansion_ratios=expansion_ratios, make_tb_flat=make_tb_flat, ) if get_primitive_standardized: to_primitive = True elif get_conventional_standardized: to_primitive = False else: to_primitive = None if to_primitive is None: out_cell = std.cell else: out_cell = std.get_standardized_cell( to_primitive=to_primitive, no_idealize=no_idealize, symprec=symprec, no_sort=no_sort, get_sort_list=get_sort_list, ) if output is not None: write_poscar(cell=out_cell, filename=output) if dump: twinpy.dump_yaml()
from copy import deepcopy import numpy as np from pymatgen.io.vasp import Poscar if __name__ == "__main__": Module_Number = int(6) Situation_Number = int(1) Diffusion_Positions = [['Oct_a', 13, 5, 29, 21, 26, 2], ['C_a', 13, 2], ['BC_b', 82, 10, 13], ['Oct_b', 66, 13]] Diffusion_Atoms = ['Al', 'Cr', 'Mo', 'Nb', 'Sn', 'Ti', 'Zr'] bottom_limit = 5.0 upper_limit = 13.0 Structure_Poscar = Poscar.from_file( "/mnt/c/Users/jackx/OneDrive/Calculation_Data/TC17_TI80/Optimistic_Structures/POSCAR_SO_M{0}_S{1}" .format(Module_Number, Situation_Number)) sd_init = np.ones((Structure_Poscar.natoms[0], 3)) for number_atom in range(0, Structure_Poscar.natoms[0]): atom_position_z = Structure_Poscar.structure[number_atom].z if atom_position_z < bottom_limit or atom_position_z > upper_limit: sd_init[number_atom] = np.zeros((1, 3)) sd_atoms = np.row_stack((sd_init, np.ones((1, 3)))) for Diffusion_Atom in Diffusion_Atoms: for Diffusion_Position in Diffusion_Positions: interstitial_postion = np.zeros(3) for Atom_Number in Diffusion_Position[1:]: interstitial_postion = interstitial_postion + Structure_Poscar.structure[ Atom_Number - 1].coords