def main(): parser = argparse.ArgumentParser() parser.add_argument('-s', '--structure', dest='structure', help='POSCAR file of the structure.') args = parser.parse_args() struc = Structure.from_file(args.structure) working_path = os.getcwd() import random import string rd_suffix = ''.join( random.choices(string.ascii_uppercase + string.digits, k=4)) vasp_path = os.path.join(working_path, 'vasp_tmp_{0:}'.format(rd_suffix)) if not os.path.exists(vasp_path): os.makedirs(vasp_path) else: shutil.rmtree(vasp_path) os.makedirs(vasp_path) relaxset = MPRelaxSet(struc, force_gamma=True, user_incar_settings={ "ISMEAR": 1, "SIGMA": 0.2 }) relaxset.write_input(vasp_path) os.chdir(vasp_path) subprocess.call("mpirun -np 10 vasp5.2-openmpi", shell=True) contcar = os.path.join(vasp_path, 'CONTCAR') dst = os.path.join(working_path, 'POSCAR_optimized') shutil.copyfile(contcar, dst)
def make_atom_mp_relax_set(): for element, potcar in PotcarSet.mp_relax_set.potcar_dict().items(): if potcar is None: continue if is_target_element(element) is False: continue structure = Structure(Lattice.cubic(10), coords=[[0.5] * 3], species=[element]) mp_set = MPRelaxSet(structure, user_kpoints_settings=Kpoints(kpts=((1, 1, 1), )), user_incar_settings={ "ALGO": "D", "ISIF": 2, "ISMEAR": 0, "MAGMOM": { "H": 1.0 }, "NELM": 300 }) Path(element).mkdir() mp_set.write_input(element)
def disorder(self,apecies,spacegroup="C2"): from pymatgen import Structure, Lattice from pymatgen.io.vasp.sets import MPRelaxSet import numpy as np import os cod=[] for i in apecies: cod.append(np.random.rand(3).tolist()) # print(cod) custom_settings = {"NELMIN": 5} specie = apecies cuau = Structure.from_spacegroup(sg=spacegroup, lattice=Lattice.cubic(10), species=apecies, coords=cod) relax = MPRelaxSet(cuau, user_incar_settings=custom_settings) os.chdir(self.dire) print (os.getcwd()) gge=[] for n in specie: for key,value in n.items(): gge.append(key) jji=[] for j in gge: jji.append(str(j)[:-2]) str1 = "-".join(jji) print (str1) relax.write_input(str(str1))
def write_vasp_files(self): """ Writes: a folder that includes vasp input file for a single structure, this is for relaxation """ mpset = MPRelaxSet(self.out_struc, user_incar_settings={'EDIFF': 1e-5, 'EDIFFG': 0.001, 'ALGO': 'F', 'ISMEAR': 0, 'ISIF': 2, 'IBRION': 2, 'NSW': 500}, \ user_kpoints_settings={'reciprocal_density': 1}) mpset.write_input(self.wd)
def Phonopy (self,mpid,supcell): from pymatgen.io.vasp.outputs import Poscar from pymatgen.io.vasp.inputs import Kpoints, Poscar from pymatgen.io.vasp.outputs import Potcar from pymatgen.io.vasp.sets import MPNMRSet from pymatgen.io.phonopy import get_displaced_structures from pymatgen.symmetry.bandstructure import HighSymmKpath import shutil import os import subprocess from pymatgen import Structure from pymatgen.io.vasp.sets import MPRelaxSet from pymatgen.ext.matproj import MPRester import shutil from shutil import copyfile import sys os.chdir(self.dire) print (os.getcwd()) # isExists=os.path.exists(mpid+"isotope") # if not isExists: # os.mkdir( mpid+"isotope" ) # print ("Directory created") # else: # print (' directory already exists') # pat = os.path.join(self.dire, mpid+"isotope") # diree = os.chdir(pat) # print (os.getcwd()) # print ("Directory entered ") mpr = MPRester() mp_id = mpid structure = mpr.get_structure_by_material_id(mp_id) relax = MPRelaxSet(structure) relax.write_input(mp_id+"isotope") print ("Input created") pat = os.path.join(self.dire, mpid+"isotope") os.chdir(pat) print (os.getcwd()) print ("Directory entered ") eb=str("phonopy -d --dim="+supcell) with open('command.bat', 'w') as file_object: file_object.write(eb ) subprocess.Popen("command.bat") for filenames in os.walk(pat): print (filenames)
def run_task(self, fw_spec): struct = self.get("structure") or fw_spec["structure"] s = Structure.from_dict(struct.as_dict()) user_incar_settings = fw_spec.get("user_incar_settings", {}) vasp_input_set = MPRelaxSet(s, user_incar_settings=user_incar_settings) dec = MontyDecoder() vis = dec.process_decoded(vasp_input_set.as_dict()) output_dir = os.getcwd() vis.write_input(output_dir=output_dir) return FWAction()
def write_vasp_files_relax(self, incar_path): """ should relax the structure again in tight criteria before running dfpt calculation pymatgen inputset may not work very well, so just copy incar from a source """ mpset = MPRelaxSet(self.struc, user_kpoints_settings={'reciprocal_density': 250}, force_gamma=True) mpset.write_input(os.path.join(self.wd, 'relax')) p = subprocess.Popen(['cp', incar_path, 'INCAR'], cwd=os.path.join(self.wd, 'relax')) p.wait()
def wf_bandstructure2D(structure, c=None): c = c or {} vasp_cmd = c.get("VASP_CMD", VASP_CMD) db_file = c.get("DB_FILE", DB_FILE) vdw_kernel = c.get("VDW_KERNEL_DIR", VDW_KERNEL_DIR) incar = _read_user_incar('Relax2D.txt') print(incar) mpr2d = MPRelaxSet(structure, force_gamma=True, user_incar_settings=incar) mpr2dstatic = MPRelaxSet(structure, force_gamma=True, user_incar_settings={ "NEDOS": "3001", "EMIN": "-15.0", "EMAX": "15.0" }) #fws = [OptimizeFW2D(structure=structure, vasp_input_set=mpr2d, vasp_cmd=vasp_cmd, db_file=db_file, vdw_kernel_dir=vdw_kernel)] fws = [ OptimizeFW2D(structure=structure, vasp_input_set=mpr2d, vasp_cmd=vasp_cmd, vdw_kernel_dir=vdw_kernel) ] fws.append(StaticFW2D(parents=fws[0], vasp_input_set=mpr2dstatic)) #fws.append(NonSCFFW2D(parents=fws[1], mode='uniform')) fws.append(NonSCFFW2D(parents=fws[1], mode='line')) wf = Workflow(fws) '''check bandstructure.yaml''' ''' wf = get_wf(structure, "bandstructure.yaml", vis=MPScanRelaxSet2D(structure, force_gamma=True,), \ params=[{'vasp_input_set': mpr2d},{},{},{}], common_params={"vasp_cmd": vasp_cmd, "db_file": db_file,}) #"vdw_kernel_dir": vdw_kernel}) ''' wf = add_common_powerups(wf, c) if c.get("SMALLGAP_KPOINT_MULTIPLY", SMALLGAP_KPOINT_MULTIPLY): wf = add_small_gap_multiply(wf, 0.5, 5, "static") wf = add_small_gap_multiply(wf, 0.5, 5, "nscf") if c.get("STABILITY_CHECK", STABILITY_CHECK): wf = add_stability_check(wf, fw_name_constraint="structure optimization") if c.get("ADD_WF_METADATA", ADD_WF_METADATA): wf = add_wf_metadata(wf, structure) wf.name = "{}:{}".format(structure.composition.reduced_formula, "bandStructure") ''' fws = wf.fws fws[0] = new_firework print(fws) ''' return wf
def download_structure(file_timestamp, download_option, data): if not file_timestamp: raise PreventUpdate structure = self.from_data(data) if isinstance(structure, StructureGraph): structure = structure.structure file_prefix = structure.composition.reduced_formula if "VASP" not in download_option: extension = self.download_options["Structure"][ download_option]["fmt"] options = self.download_options["Structure"][download_option] try: contents = structure.to(**options) except Exception as exc: # don't fail silently, tell user what went wrong contents = exc base64 = b64encode(contents.encode("utf-8")).decode("ascii") download_data = { "content": base64, "base64": True, "type": "text/plain", "filename": f"{file_prefix}.{extension}", } else: if "Relax" in download_option: vis = MPRelaxSet(structure) expected_filename = "MPRelaxSet.zip" else: raise ValueError( "No other VASP input sets currently supported.") with TemporaryDirectory() as tmpdir: vis.write_input(tmpdir, potcar_spec=True, zip_output=True) path = Path(tmpdir) / expected_filename bytes = b64encode(path.read_bytes()).decode("ascii") download_data = { "content": bytes, "base64": True, "type": "application/zip", "filename": f"{file_prefix} {expected_filename}", } return download_data
def phase_sol(self, EB_K_2, judge='', appendage=""): import os from pymatgen import Structure from pymatgen.io.vasp.sets import MPRelaxSet from pymatgen import Structure, Lattice, MPRester, Molecule import shutil ass = self.cif_route print(ass) # os.chdir(r"D:\Desktop\VASP practical\Input") # print (os.getcwd()) # Note that you must provide your own API Key, which can # be accessed via the Dashboard at materialsproject.org #mpr = MPRester()#密钥 molecule = Molecule.from_file(ass) structure = molecule.get_boxed_structure(self.a, self.b, self.c) print(structure) os.chdir(r"D:\Desktop\VASP practical\Input") print(os.getcwd()) custom_settings = {"NELMIN": 5} # user custom incar settings relax = MPRelaxSet(structure, user_incar_settings=custom_settings) os.chdir(r"D:\Desktop\VASP practical\Input") print(os.getcwd()) relax.write_input(ass + '---' + "sol" + str(EB_K_2) + 'phase') os.chdir("./" + ass + '---' + "sol" + str(EB_K_2) + 'phase') #定义一个更改当前目录的变量 dire2 = './vaspstd_sub' #确立脚本名称 shutil.copy(r"C:\Users\41958\.spyder-py3\vaspstd_sub", dire2) eb = str(EB_K_2) #将介电常数参数作为字符串 ls = str('TURE') #加入开启溶剂参数 with open('INCAR', 'a') as file_object: file_object.write('LSOL = ' + ls + '\n' + 'EB_K = ' + eb) #将两个参数写入INCAR eb = appendage #储存WAVECAR with open('INCAR', 'r') as f1: lines = f1.readlines() with open('INCAR', 'w') as f2: for line in lines: if judge in line: continue f2.write(line) with open('INCAR', 'a') as f3: f3.write(eb) os.chdir(r"D:\Desktop\VASP practical\workdir") print(os.getcwd())
def phase(self, judge='', appendage=""): import os import re from pymatgen import Structure from pymatgen.io.vasp.sets import MPRelaxSet from pymatgen.io.cif import CifParser import shutil ass = self.cif_route print(ass) # os.chdir(r"E:\VASP practical\Input") # print (os.getcwd()) # Note that you must provide your own API Key, which can # be accessed via the Dashboard at materialsproject.org #mpr = MPRester()#密钥 struct = CifParser(ass) structure = struct.get_structures()[0] print(structure) os.chdir(r"E:\VASP practical\Input") print(os.getcwd()) structure.make_supercell(self.supercell) custom_settings = {"NPAR": 4} # user custom incar settings relax = MPRelaxSet(structure, user_incar_settings=custom_settings) os.chdir(r"E:\VASP practical\Input") print(os.getcwd()) relax.write_input(ass + '---' + 'phase') os.chdir("./" + ass + '---' + 'phase') #定义一个更改当前目录的变量 dire2 = './vaspstd_sub' #确立脚本名称 shutil.copy(r"C:\Users\41958\.spyder-py3\vaspstd_sub", dire2) eb = appendage #储存WAVECAR with open('INCAR', 'r') as f1: lines = f1.readlines() with open('INCAR', 'w') as f2: for line in lines: if judge in line: continue f2.write(line) with open('INCAR', 'a') as f3: f3.write(eb) #将两个参数写入INCAR os.chdir(r"D:\Desktop\VASP practical\workdir") print(os.getcwd())
def test_setup(self): try: vi = MPRelaxSet(self.struct_si, force_gamma=True) vi.write_input(".") except ValueError: import traceback traceback.print_exc() help_str = "This system is not set up to run VASP jobs. See further error tracebacks " \ "for help. Try making sure your PMG_VASP_PSP_DIR has the proper subdirs as " \ "outlined in PotcarSingle class of pymatgen, e.g. POT_GGA_PAW_PBE subdir." raise ValueError(help_str) self._verify_files()
def wf_thermal_expansion(structure, c=None): """ Thermal expansion coefficient workflow from the given structure and config dict. Args: structure (Structure): input structure c (dict): workflow config dict Returns: Workflow """ c = c or {} eos = c.get("EOS", "vinet") vasp_cmd = c.get("VASP_CMD", VASP_CMD) db_file = c.get("DB_FILE", DB_FILE) pressure = c.get("PRESSURE", 0.0) user_kpoints_settings = {"grid_density": 7000} # 10 deformations deformations = [(np.identity(3) * (1 + x)).tolist() for x in np.linspace(-0.1, 0.1, 10)] tag = "thermal_expansion group: >>{}<<".format(str(uuid4())) # input set for structure optimization vis_relax = MPRelaxSet(structure, force_gamma=True) v = vis_relax.as_dict() v.update({"user_kpoints_settings": user_kpoints_settings}) vis_relax = vis_relax.__class__.from_dict(v) # optimization only workflow wf = get_wf(structure, "optimize_only.yaml", params=[{"vasp_cmd": vasp_cmd, "db_file": db_file, "name": "{} structure optimization".format(tag)}], vis=vis_relax) wf_thermal = get_wf_thermal_expansion(structure, user_kpoints_settings=user_kpoints_settings, deformations=deformations, vasp_cmd=vasp_cmd, db_file=db_file, eos=eos, pressure=pressure, tag=tag) # chain it wf.append_wf(wf_thermal, wf.leaf_fw_ids) wf = add_modify_incar(wf, modify_incar_params={"incar_update": {"ENCUT": 600, "EDIFF": 1e-6}}) wf = add_common_powerups(wf, c) if c.get("ADD_WF_METADATA", ADD_WF_METADATA): wf = add_wf_metadata(wf, structure) return wf
def __init__(self, mp_id, incar_settings: dict): self.mp_id = str(mp_id) self.structure = mpr.get_structure_by_material_id(self.mp_id) self.primitive_structure = self.structure.get_primitive_structure() self.kpath = HighSymmKpath(self.primitive_structure) # self.new_kpoints = self.add_kpoints(self.kpath) self.add_kpoints(self.kpath) # Add inverse kpoints intp kpath.__dict__['kpoints '] self.relaxed_structure = MPRelaxSet(self.structure, user_incar_settings=incar_settings) self.relaxed_structure.potcar_functional = 'PW91' # Vasp functional set as potpaw_GGA
def __init__(self, structure, name="structure optimization", vasp_input_set=None, vasp_cmd=VASP_CMD, override_default_vasp_params=None, ediffg=None, db_file=DB_FILE, force_gamma=True, job_type="double_relaxation_run", max_force_threshold=RELAX_MAX_FORCE, auto_npar=">>auto_npar<<", half_kpts_first_relax=HALF_KPOINTS_FIRST_RELAX, parents=None, **kwargs): """ Optimize the given structure. Args: structure (Structure): Input structure. name (str): Name for the Firework. vasp_input_set (VaspInputSet): input set to use. Defaults to MPRelaxSet() if None. override_default_vasp_params (dict): If this is not None, these params are passed to the default vasp_input_set, i.e., MPRelaxSet. This allows one to easily override some settings, e.g., user_incar_settings, etc. vasp_cmd (str): Command to run vasp. ediffg (float): Shortcut to set ediffg in certain jobs db_file (str): Path to file specifying db credentials to place output parsing. force_gamma (bool): Force gamma centered kpoint generation job_type (str): custodian job type (default "double_relaxation_run") max_force_threshold (float): max force on a site allowed at end; otherwise, reject job auto_npar (bool or str): whether to set auto_npar. defaults to env_chk: ">>auto_npar<<" half_kpts_first_relax (bool): whether to use half the kpoints for the first relaxation parents ([Firework]): Parents of this particular Firework. \*\*kwargs: Other kwargs that are passed to Firework.__init__. """ override_default_vasp_params = override_default_vasp_params or {} vasp_input_set = vasp_input_set or MPRelaxSet( structure, force_gamma=force_gamma, **override_default_vasp_params) t = [] t.append( WriteVaspFromIOSet(structure=structure, vasp_input_set=vasp_input_set)) t.append( RunVaspCustodian(vasp_cmd=vasp_cmd, job_type=job_type, max_force_threshold=max_force_threshold, ediffg=ediffg, auto_npar=auto_npar, half_kpts_first_relax=half_kpts_first_relax)) t.append(PassCalcLocs(name=name)) t.append( VaspToDb(db_file=db_file, additional_fields={"task_label": name})) super(OptimizeFW, self).__init__(t, parents=parents, name="{}-{}".format( structure.composition.reduced_formula, name), **kwargs)
def wf_bandstructure_plus_boltztrap(structure, c=None): c = c or {} vasp_cmd = c.get("VASP_CMD", VASP_CMD) db_file = c.get("DB_FILE", DB_FILE) params = [] for x in range(4): # everything but BoltzTrap task params.append({"vasp_cmd": vasp_cmd, "db_file": db_file}) params.append({"db_file": db_file}) wf = get_wf( structure, "bandstructure_boltztrap.yaml", vis=MPRelaxSet(structure, force_gamma=True), params=params, ) wf = add_common_powerups(wf, c) if c.get("SMALLGAP_KPOINT_MULTIPLY", SMALLGAP_KPOINT_MULTIPLY): wf = add_small_gap_multiply(wf, 0.5, 5, "static") wf = add_small_gap_multiply(wf, 0.5, 5, "nscf") if c.get("STABILITY_CHECK", STABILITY_CHECK): wf = add_stability_check(wf, fw_name_constraint="structure optimization") if c.get("ADD_WF_METADATA", ADD_WF_METADATA): wf = add_wf_metadata(wf, structure) return wf
def Write_Vasp_POTCAR(cal_loc, structure_filename, workflow): """ Write POTCAR in folder cal_loc as follows: If POTCAR is missing, write POTCAR using pymatgen.io.vasp.sets.MPRelaxSet Input arguments: cal_loc (str): the absolute path structure_filename (str): the file from which the structure is read using pymatgen.Structure.from_file workflow """ firework = get_current_firework_from_cal_loc(cal_loc, workflow) log_txt_loc, firework_name = os.path.split(cal_loc) log_txt = os.path.join(log_txt_loc, "log.txt") if not os.path.isfile(os.path.join(cal_loc, "POTCAR")): structure = Structure.from_file( os.path.join(cal_loc, structure_filename)) vis = MPRelaxSet(structure=structure) vis.potcar.write_file(filename=os.path.join(cal_loc, "POTCAR")) write_INCAR = True with open(log_txt, "a") as f: f.write("{} INFO: no POTCAR in {}\n".format( get_time_str(), firework_name)) f.write( "\t\t\tuse pymatgen.io.vasp.sets.MPRelaxSet to write POTCAR\n")
def test_ioset_explicit(self): ft = WriteVaspFromIOSet( dict(structure=self.struct_si, vasp_input_set=MPRelaxSet(self.struct_si, force_gamma=True))) ft = load_object(ft.to_dict()) # simulate database insertion ft.run_task({}) self._verify_files()
def test_bandgap_check_Vasp(self): # add the workflow structure = self.struct_si # instructs to use db_file set by FWorker, see env_chk my_wf = get_wf(structure, "bandstructure.yaml", vis=MPRelaxSet(structure, force_gamma=True), common_params={ "vasp_cmd": VASP_CMD, "db_file": ">>db_file<<" }) if not VASP_CMD: my_wf = use_fake_vasp(my_wf, ref_dirs_si) else: my_wf = use_custodian(my_wf) my_wf = add_namefile(my_wf) # add a slug of fw-name to output files my_wf = add_bandgap_check(my_wf, check_bandgap_params={"max_gap": 0.1}, fw_name_constraint="structure optimization") self.lp.add_wf(my_wf) # run the workflow # set the db_file variable rapidfire(self.lp, fworker=_fworker) # structure optimization should be completed self.assertEqual( self.lp.fireworks.find_one({"name": "Si-structure optimization"}, {"state": 1})["state"], "COMPLETED") self.assertEqual( self.lp.fireworks.find_one({"name": "Si-static"}, {"state": 1})["state"], "DEFUSED")
def test_trackers(self): # add the workflow structure = self.struct_si my_wf = get_wf(structure, "optimize_only.yaml", vis=MPRelaxSet(structure, force_gamma=True), common_params={"vasp_cmd": VASP_CMD}) if not VASP_CMD: my_wf = use_fake_vasp(my_wf, ref_dirs_si) else: my_wf = use_custodian(my_wf) my_wf = add_trackers(my_wf) self.lp.add_wf(my_wf) # run the workflow rapidfire(self.lp, fworker=_fworker) for x in self.lp.get_tracker_data(1): for t in x["trackers"]: self.assertGreater(len(t.content.split("\n")), 20) wf = self.lp.get_wf_by_fw_id(1) self.assertTrue(all([s == 'COMPLETED' for s in wf.fw_states.values()]))
def wf_bandstructure(structure, c=None): c = c or {} vasp_cmd = c.get("VASP_CMD", VASP_CMD) db_file = c.get("DB_FILE", DB_FILE) wf = get_wf(structure, "bandstructure.yaml", vis=MPRelaxSet(structure, force_gamma=True), common_params={ "vasp_cmd": vasp_cmd, "db_file": db_file }) wf = add_common_powerups(wf, c) if c.get("SMALLGAP_KPOINT_MULTIPLY", SMALLGAP_KPOINT_MULTIPLY): wf = add_small_gap_multiply(wf, 0.5, 5, "static") wf = add_small_gap_multiply(wf, 0.5, 5, "nscf") if c.get("STABILITY_CHECK", STABILITY_CHECK): wf = add_stability_check(wf, fw_name_constraint="structure optimization") if c.get("ADD_WF_METADATA", ADD_WF_METADATA): wf = add_wf_metadata(wf, structure) return wf
def test_single_Vasp_dbinsertion(self): # add the workflow structure = self.struct_si # instructs to use db_file set by FWorker, see env_chk my_wf = get_wf(structure, "optimize_only.yaml", vis=MPRelaxSet(structure, force_gamma=True), common_params={ "vasp_cmd": VASP_CMD, "db_file": ">>db_file<<" }) if not VASP_CMD: my_wf = use_fake_vasp(my_wf, ref_dirs_si) else: my_wf = use_custodian(my_wf) # add an msonable object to additional fields my_wf.fws[0].tasks[-1]['additional_fields'].update( {"test_additional_field": self.struct_si}) self.lp.add_wf(my_wf) # run the workflow rapidfire(self.lp, fworker=_fworker) d = self.get_task_collection().find_one() self._check_run(d, mode="structure optimization") self._check_run(d, mode="additional field") wf = self.lp.get_wf_by_fw_id(1) self.assertTrue(all([s == 'COMPLETED' for s in wf.fw_states.values()]))
def wf_structure_optimization(structure, c=None): c = c or {} vasp_cmd = c.get("VASP_CMD", VASP_CMD) db_file = c.get("DB_FILE", DB_FILE) user_incar_settings = c.get("USER_INCAR_SETTINGS") wf = get_wf( structure, "optimize_only.yaml", vis=MPRelaxSet(structure, force_gamma=True, user_incar_settings=user_incar_settings), common_params={ "vasp_cmd": vasp_cmd, "db_file": db_file }, ) wf = add_common_powerups(wf, c) if c.get("ADD_WF_METADATA", ADD_WF_METADATA): wf = add_wf_metadata(wf, structure) return wf
def run_task(self, fw_spec): chgcar_start = False # read the VaspInput from the previous run poscar = Poscar.from_file(zpath('POSCAR')) incar = Incar.from_file(zpath('INCAR')) # figure out what GGA+U values to use and override them # LDAU values to use mpvis = MPRelaxSet(poscar.structure) ggau_incar = mpvis.incar.as_dict() incar_updates = { k: ggau_incar[k] for k in ggau_incar.keys() if 'LDAU' in k } for k in ggau_incar: # update any parameters not set explicitly in previous INCAR if k not in incar and k in ggau_incar: incar_updates[k] = ggau_incar[k] incar.update(incar_updates) # override the +U keys # start from the CHGCAR of previous run if os.path.exists('CHGCAR'): incar['ICHARG'] = 1 chgcar_start = True # write back the new INCAR to the current directory incar.write_file('INCAR') return FWAction(stored_data={'chgcar_start': chgcar_start})
def test_single_Vasp_dbinsertion(self): # add the workflow structure = self.struct_si # instructs to use db_file set by FWorker, see env_chk my_wf = get_wf(structure, "optimize_only.yaml", vis=MPRelaxSet(structure, force_gamma=True), common_params={ "vasp_cmd": VASP_CMD, "db_file": ">>db_file<<" }) if not VASP_CMD: my_wf = use_fake_vasp(my_wf, ref_dirs_si) else: my_wf = use_custodian(my_wf) self.lp.add_wf(my_wf) # run the workflow # set the db_file variable rapidfire( self.lp, fworker=FWorker(env={"db_file": os.path.join(db_dir, "db.json")})) d = self.get_task_collection().find_one() self._check_run(d, mode="structure optimization") wf = self.lp.get_wf_by_fw_id(1) self.assertTrue(all([s == 'COMPLETED' for s in wf.fw_states.values()]))
def PBEsol_relaxation(self,output_dir='./'): path = os.path.join(output_dir,self.name) inputs = MPRelaxSet(self.stru).all_input incar = inputs['INCAR'] if self.is_spin_polarized: incar['ISPIN']=2 else: incar['ISPIN']=1 enmax = round(max([i.PSCTR['ENMAX'] for i in inputs['POTCAR']])*1.3) incar['ENCUT'] = int(enmax) incar["SYSTEM"]=self.name + "_PBEsol_Relax" incar["ALGO"] = "Normal" incar["EDIFF"] = 0.0001 incar["EDIFFG"] = 0.001 incar["ISMEAR"] = 0 incar["GGA"] = "PS" incar["NSW"] = 99 profile = {'source':self.mpid,'calculation':'PBEsol_relaxation'} os.mkdir(path) f=open(os.path.join(path,'profile.json'),'w') f.write(json.dumps(jsanitize(profile))) inputs['KPOINTS'].write_file(path+"/KPOINTS") inputs['POSCAR'].write_file(path+"/POSCAR") inputs['POTCAR'].write_file(path+"/POTCAR") incar.write_file(path+"/INCAR")
def _snl_to_spec(snl, enforce_gga=False, parameters=None): parameters = parameters if parameters else {} parameters.setdefault('boltztrap', True) # by default run boltztrap parameters.setdefault('force_gamma', False) # by default not force gamma parameters.setdefault('exact_structure', True) spec = {'parameters': parameters} incar_enforce = {'NCORE': 8} if parameters['exact_structure']: structure = snl.structure else: structure = snl.structure.get_primitive_structure() if enforce_gga: incar_enforce.update({"LDAU": False}) mpvis = MPRelaxSet(structure, user_incar_settings=incar_enforce, force_gamma=parameters['force_gamma']) incar = mpvis.incar poscar = mpvis.poscar kpoints = mpvis.kpoints potcar = mpvis.potcar spec['vasp'] = {} spec['vasp']['incar'] = incar.as_dict() spec['vasp']['poscar'] = poscar.as_dict() spec['vasp']['kpoints'] = kpoints.as_dict() spec['vasp']['potcar'] = potcar.as_dict() # Add run tags of pseudopotential spec['run_tags'] = spec.get('run_tags', [potcar.functional]) spec['run_tags'].extend(potcar.symbols) # Add run tags of +U u_tags = [ '%s=%s' % t for t in zip(poscar.site_symbols, incar.get('LDAUU', [0] * len(poscar.site_symbols))) ] spec['run_tags'].extend(u_tags) # add user run tags if 'run_tags' in parameters: spec['run_tags'].extend(parameters['run_tags']) del spec['parameters']['run_tags'] # add exact structure run tag automatically if we have a unique situation if 'exact_structure' in parameters and parameters['exact_structure'] and \ structure != snl.structure.get_primitive_structure(): spec['run_tags'].extend('exact_structure') spec['_dupefinder'] = DupeFinderVasp().to_dict() spec['vaspinputset_name'] = mpvis.__class__.__name__ spec['task_type'] = 'GGA+U optimize structure (2x)' if spec['vasp'][ 'incar'].get('LDAU', False) else 'GGA optimize structure (2x)' return spec
def make_atom_mp_relax_set(): for element, potcar in PotcarSet.mp_relax_set.potcar_dict().items(): if potcar is None: continue Path(element).mkdir() structure = Structure(Lattice.cubic(10), coords=[[0.5] * 3], species=[element]) mp_set = MPRelaxSet(structure, user_kpoints_settings=Kpoints(kpts=((1, 1, 1), )), user_incar_settings={ "ISIF": 2, "ISMEAR": 0, "NUPDOWN": nupdown[element], "NELM": 300 }) mp_set.write_input(element)
def test_pmgobjects(self): mpvis = MPRelaxSet(self.struct_si, force_gamma=True) ft = WriteVaspFromPMGObjects({"incar": mpvis.incar, "poscar": mpvis.poscar, "kpoints": mpvis.kpoints, "potcar": mpvis.potcar}) ft = load_object(ft.to_dict()) # simulate database insertion ft.run_task({}) self._verify_files()
def setUpClass(cls): struct_si = PymatgenTest.get_structure("Si") vis = MPRelaxSet(struct_si, force_gamma=True) cls.bs_wf = get_wf(struct_si, "bandstructure.yaml", vis=vis, common_params={"vasp_cmd": "test_VASP"}) cls.bsboltz_wf = get_wf(struct_si, "bandstructure_boltztrap.yaml", vis=vis)
def __init__(self, structures, unset_encut=False, **kwargs): if len(structures) < 3: raise ValueError("You need at least 3 structures for an NEB.") kwargs["sort_structure"] = False MPRelaxSet.__init__(self, structures[0], **kwargs) self.structures = self._process_structures(structures) self.unset_encut = False if unset_encut: self.config_dict["INCAR"].pop("ENCUT", None) if "EDIFF" not in self.config_dict["INCAR"]: self.config_dict["INCAR"]["EDIFF"] = self.config_dict[ "INCAR"].pop("EDIFF_PER_ATOM") # NEB specific defaults defaults = {'IMAGES': len(structures) - 2, 'IBRION': 1, 'ISYM': 0, 'LCHARG': False, "LDAU": False} self.config_dict["INCAR"].update(defaults)