def setup(self): """ setup static jobs for all the calibrate objects copies CONTCAR to POSCAR sets NSW = 0 """ for cal in self.cal_objs: for i, jdir in enumerate(cal.old_job_dir_list): job_dir = self.job_dir + os.sep \ + jdir.replace(os.sep, '_').replace('.', '_') \ + os.sep + 'STATIC' logger.info('setting up job in {}'.format(job_dir)) cal.incar = Incar.from_file(jdir + os.sep + 'INCAR') cal.incar['EDIFF'] = '1E-6' cal.incar['NSW'] = 0 cal.potcar = Potcar.from_file(jdir + os.sep + 'POTCAR') cal.kpoints = Kpoints.from_file(jdir + os.sep + 'KPOINTS') contcar_file = jdir + os.sep + 'CONTCAR' if os.path.isfile(contcar_file): logger.info('setting poscar file from {}' .format(contcar_file)) cal.poscar = Poscar.from_file(contcar_file) cal.add_job(job_dir=job_dir) else: logger.critical("""CONTCAR doesnt exist. Setting up job using input set in the old calibration directory""") cal.poscar = Poscar.from_file(jdir + os.sep + 'POSCAR') cal.add_job(job_dir=job_dir)
def test_kpt_bands_as_dict_from_dict(self): file_name = os.path.join(test_dir, 'KPOINTS.band') k = Kpoints.from_file(file_name) d = k.as_dict() import json json.dumps(d) # This doesn't work k2 = Kpoints.from_dict(d) self.assertEqual(k.kpts, k2.kpts) self.assertEqual(k.style, k2.style) self.assertEqual(k.kpts_shift, k2.kpts_shift) self.assertEqual(k.num_kpts, k2.num_kpts)
def test_kpt_bands_as_dict_from_dict(self): file_name = os.path.join(test_dir, 'KPOINTS.band') k = Kpoints.from_file(file_name) d = k.as_dict() import json json.dumps(d) #This doesn't work k2 = Kpoints.from_dict(d) self.assertEqual(k.kpts, k2.kpts) self.assertEqual(k.style, k2.style) self.assertEqual(k.kpts_shift, k2.kpts_shift) self.assertEqual(k.num_kpts, k2.num_kpts)
def setUp(self): filepath = self.TEST_FILES_DIR / 'INCAR' incar = Incar.from_file(filepath) filepath = self.TEST_FILES_DIR / 'POSCAR' poscar = Poscar.from_file(filepath,check_for_POTCAR=False) if "PMG_VASP_PSP_DIR" not in os.environ: os.environ["PMG_VASP_PSP_DIR"] = str(self.TEST_FILES_DIR) filepath = self.TEST_FILES_DIR / 'POTCAR' potcar = Potcar.from_file(filepath) filepath = self.TEST_FILES_DIR / 'KPOINTS.auto' kpoints = Kpoints.from_file(filepath) self.vinput = VaspInput(incar, kpoints, poscar, potcar)
def setUp(self): filepath = self.TEST_FILES_DIR / 'INCAR' incar = Incar.from_file(filepath) filepath = self.TEST_FILES_DIR / 'POSCAR' poscar = Poscar.from_file(filepath, check_for_POTCAR=False) if "PMG_VASP_PSP_DIR" not in os.environ: os.environ["PMG_VASP_PSP_DIR"] = str(self.TEST_FILES_DIR) filepath = self.TEST_FILES_DIR / 'POTCAR' potcar = Potcar.from_file(filepath) filepath = self.TEST_FILES_DIR / 'KPOINTS.auto' kpoints = Kpoints.from_file(filepath) self.vinput = VaspInput(incar, kpoints, poscar, potcar)
def setUp(self): filepath = PymatgenTest.TEST_FILES_DIR / "INCAR" incar = Incar.from_file(filepath) filepath = PymatgenTest.TEST_FILES_DIR / "POSCAR" poscar = Poscar.from_file(filepath, check_for_POTCAR=False) if "PMG_VASP_PSP_DIR" not in os.environ: os.environ["PMG_VASP_PSP_DIR"] = str(PymatgenTest.TEST_FILES_DIR) filepath = PymatgenTest.TEST_FILES_DIR / "POTCAR" potcar = Potcar.from_file(filepath) filepath = PymatgenTest.TEST_FILES_DIR / "KPOINTS.auto" kpoints = Kpoints.from_file(filepath) self.vinput = VaspInput(incar, kpoints, poscar, potcar)
def __init__(self, folder, projected=False, hse=False, spin='up', kpath=None, n=None): """ Initialize parameters upon the generation of this class Inputs: ---------- folder: (str) This is the folder that contains the VASP files projected: (bool) Determined wheter of not to parte the projected eigenvalues from the vasprun.xml file. Making this true increases the computational time, so only use if a projected band structure is required. hse: (bool) Determines if the KPOINTS file is in the form of HSE or not. Only make true if the band structure was calculated using a hybrid functional. spin: (str) Choose which spin direction to parse. ('up' or 'down') """ self.vasprun = BSVasprun(f'{folder}/vasprun.xml', parse_projected_eigen=projected) self.poscar = Poscar.from_file(f'{folder}/POSCAR', check_for_POTCAR=False, read_velocities=False) self.projected = projected self.hse = hse self.kpath = kpath self.n = n self.folder = folder self.spin = 'up' self.spin_dict = {'up': Spin.up, 'dowm': Spin.down} self.bands_dict = self.load_bands() self.color_dict = { 0: '#FF0000', 1: '#0000FF', 2: '#008000', 3: '#800080', 4: '#E09200', 5: '#FF5C77', 6: '#778392', 7: '#07C589', 8: '#40BAF2', } if projected: self.projected_dict = self.load_projected_bands() if not hse: self.kpoints = Kpoints.from_file(f'{folder}/KPOINTS')
def test_kpt_bands_as_dict_from_dict(self): file_name = self.TEST_FILES_DIR / "KPOINTS.band" k = Kpoints.from_file(file_name) d = k.as_dict() import json json.dumps(d) # This doesn't work k2 = Kpoints.from_dict(d) self.assertEqual(k.kpts, k2.kpts) self.assertEqual(k.style, k2.style) self.assertEqual(k.kpts_shift, k2.kpts_shift) self.assertEqual(k.num_kpts, k2.num_kpts)
def test_write_inputset(self): name = 'Test' incar= Incar.from_file(TEST_STEP1+os.sep+'INCAR') kpoints = Kpoints.from_file(TEST_STEP1+os.sep+'KPOINTS') poscar = Poscar.from_file(TEST_STEP1+os.sep+'POSCAR') potcar = TEST_STEP1+os.sep+'DUMMY_POTSPEC' #potcar = #Potcar.from_dict({'@class': 'Potcar', 'functional': 'PBE',\ # 'symbols': ['Al'], '@module': 'pymatgen.io.vasp.inputs'}) reuse_path = [TEST_STEP1 + os.sep + 'COPY_FILE'] print (reuse_path) mvis = MPINTVaspInputSet(name,incar,poscar,potcar,kpoints,reuse_path=reuse_path,test=True) mvis.write_input(job_dir=TEST_STEP2) self.assertCountEqual(os.listdir(TEST_STEP2), ['INCAR','KPOINTS','POSCAR','COPY_FILE']) cleanup = [os.remove(TEST_STEP2+os.sep+f) for f in os.listdir(TEST_STEP2)]
def get_nelec_LHFCALC(self, dir): pos = Poscar.from_file(os.path.join(dir, 'POSCAR')) pot = Potcar.from_file(os.path.join(dir, 'POTCAR')) incar = Incar.from_file(os.path.join(dir, 'INCAR')) kpt = Kpoints.from_file(os.path.join(dir, 'KPOINTS')) if 'LHFCALC' in incar: LHFCALC = incar['LHFCALC'] else: LHFCALC = False natoms = pos.natoms nelec_atom = [i.nelectrons for i in pot] nelec_elt = np.array(natoms) * np.array(nelec_atom) nelec_sum = nelec_elt.sum() return (nelec_sum, LHFCALC)
def setUp(self): filepath = os.path.join(test_dir, 'INCAR') incar = Incar.from_file(filepath) filepath = os.path.join(test_dir, 'POSCAR') poscar = Poscar.from_file(filepath,check_for_POTCAR=False) if "PMG_VASP_PSP_DIR" not in os.environ: test_potcar_dir = os.path.abspath( os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "test_files")) os.environ["PMG_VASP_PSP_DIR"] = test_potcar_dir filepath = os.path.join(test_dir, 'POTCAR') potcar = Potcar.from_file(filepath) filepath = os.path.join(test_dir, 'KPOINTS.auto') kpoints = Kpoints.from_file(filepath) self.vinput = VaspInput(incar, kpoints, poscar, potcar)
def _parse_ibzkpt(ibzkpt): if ibzkpt: try: ibz = Kpoints.from_file(ibzkpt) if ibz.tet_number != 0: logging.error("\nERROR: IBZKPT contains tetrahedron " "information.") sys.exit() except OSError: logging.error("\nERROR: Hybrid specified but no IBZKPT file " "found.") sys.exit() else: ibz = None return ibz
def setUp(self): filepath = os.path.join(test_dir, "INCAR") incar = Incar.from_file(filepath) filepath = os.path.join(test_dir, "POSCAR") poscar = Poscar.from_file(filepath) if "VASP_PSP_DIR" not in os.environ: test_potcar_dir = os.path.abspath( os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "test_files") ) os.environ["VASP_PSP_DIR"] = test_potcar_dir filepath = os.path.join(test_dir, "POTCAR") potcar = Potcar.from_file(filepath) filepath = os.path.join(test_dir, "KPOINTS.auto") kpoints = Kpoints.from_file(filepath) self.vinput = VaspInput(incar, kpoints, poscar, potcar)
def test_init(self): prev_run = os.path.join(test_dir, "relaxation") vis = MPNonSCFSet.from_prev_calc(prev_calc_dir=prev_run, mode="Line", copy_chgcar=False) self.assertEqual(vis.incar["NSW"], 0) # Check that the ENCUT has been inherited. self.assertEqual(vis.incar["ENCUT"], 600) self.assertEqual(vis.kpoints.style, Kpoints.supported_modes.Reciprocal) # Check as from dict. vis = MPNonSCFSet.from_dict(vis.as_dict()) self.assertEqual(vis.incar["NSW"], 0) # Check that the ENCUT has been inherited. self.assertEqual(vis.incar["ENCUT"], 600) self.assertEqual(vis.kpoints.style, Kpoints.supported_modes.Reciprocal) vis.write_input(self.tmp) self.assertFalse(os.path.exists(os.path.join(self.tmp, "CHGCAR"))) vis = MPNonSCFSet.from_prev_calc(prev_calc_dir=prev_run, mode="Line", copy_chgcar=True) vis.write_input(self.tmp) self.assertTrue(os.path.exists(os.path.join(self.tmp, "CHGCAR"))) # Code below is just to make sure that the parameters are the same # between the old MPStaticVaspInputSet and the new MPStaticSet. # TODO: Delete code below in future. MPNonSCFVaspInputSet.from_previous_vasp_run(previous_vasp_dir=prev_run, output_dir=self.tmp, mode="Line") incar = Incar.from_file(os.path.join(self.tmp, "INCAR")) for k, v1 in vis.incar.items(): v2 = incar.get(k) try: v1 = v1.upper() v2 = v2.upper() except: # Convert strings to upper case for comparison. Ignore other # types. pass self.assertEqual(v1, v2, str(v1) + str(v2)) kpoints = Kpoints.from_file(os.path.join(self.tmp, "KPOINTS")) self.assertEqual(kpoints.style, vis.kpoints.style) self.assertArrayAlmostEqual(kpoints.kpts, vis.kpoints.kpts)
def setup(self): """ setup solvation jobs for the calibrate objects copies WAVECAR and sets the solvation params in the incar file also dumps system.json file in each directory for the database crawler mind: works only for cal objects that does only single calculations """ for cal in self.cal_objs: jdir = cal.old_job_dir_list[0] cal.poscar = Poscar.from_file(jdir + os.sep + 'POSCAR') cal.potcar = Potcar.from_file(jdir + os.sep + 'POTCAR') cal.kpoints = Kpoints.from_file(jdir + os.sep + 'KPOINTS') cal.incar = Incar.from_file(jdir + os.sep + 'INCAR') cal.incar['LSOL'] = '.TRUE.' syms = [site.specie.symbol for site in cal.poscar.structure] zvals = {p.symbol: p.nelectrons for p in cal.potcar} nelectrons = sum([ zvals[a[0]] * len(tuple(a[1])) for a in itertools.groupby(syms) ]) keys = [k for k in self.sol_params.keys() if self.sol_params[k]] prod_list = [self.sol_params.get(k) for k in keys] for params in itertools.product(*tuple(prod_list)): job_dir = self.job_dir + os.sep \ + cal.old_job_dir_list[0].replace(os.sep, '_').replace('.', '_') \ + os.sep + 'SOL' for i, k in enumerate(keys): if k == 'NELECT': cal.incar[k] = params[i] + nelectrons else: cal.incar[k] = params[i] job_dir = job_dir + os.sep + k + os.sep + str( cal.incar[k]).replace('.', '_') if not os.path.exists(job_dir): os.makedirs(job_dir) with open(job_dir + os.sep + 'system.json', 'w') as f: json.dump(dict(list(zip(keys, params))), f) wavecar_file = cal.old_job_dir_list[0] + os.sep + 'WAVECAR' if os.path.isfile(wavecar_file): shutil.copy(wavecar_file, job_dir + os.sep + 'WAVECAR') cal.add_job(job_dir=job_dir) else: logger.critical('WAVECAR doesnt exist. Aborting ...') sys.exit(0)
def setup(self): """ setup solvation jobs for the calibrate objects copies WAVECAR and sets the solvation params in the incar file also dumps system.json file in each directory for the database crawler mind: works only for cal objects that does only single calculations """ for cal in self.cal_objs: jdir = cal.old_job_dir_list[0] cal.poscar = Poscar.from_file(jdir + os.sep + 'POSCAR') cal.potcar = Potcar.from_file(jdir + os.sep + 'POTCAR') cal.kpoints = Kpoints.from_file(jdir + os.sep + 'KPOINTS') cal.incar = Incar.from_file(jdir + os.sep + 'INCAR') cal.incar['LSOL'] = '.TRUE.' syms = [site.specie.symbol for site in cal.poscar.structure] zvals = {p.symbol: p.nelectrons for p in cal.potcar} nelectrons = sum([zvals[a[0]] * len(tuple(a[1])) for a in itertools.groupby(syms)]) keys = [k for k in self.sol_params.keys() if self.sol_params[k]] prod_list = [self.sol_params.get(k) for k in keys] for params in itertools.product(*tuple(prod_list)): job_dir = self.job_dir + os.sep \ + cal.old_job_dir_list[0].replace(os.sep, '_').replace('.', '_') \ + os.sep + 'SOL' for i, k in enumerate(keys): if k == 'NELECT': cal.incar[k] = params[i] + nelectrons else: cal.incar[k] = params[i] job_dir = job_dir + os.sep + k + os.sep + str( cal.incar[k]).replace('.', '_') if not os.path.exists(job_dir): os.makedirs(job_dir) with open(job_dir + os.sep + 'system.json', 'w') as f: json.dump(dict(list(zip(keys, params))), f) wavecar_file = cal.old_job_dir_list[0] + os.sep + 'WAVECAR' if os.path.isfile(wavecar_file): shutil.copy(wavecar_file, job_dir + os.sep + 'WAVECAR') cal.add_job(job_dir=job_dir) else: logger.critical('WAVECAR doesnt exist. Aborting ...') sys.exit(0)
def setup(self): """ setup static jobs for the calibrate objects copies CONTCAR to POSCAR sets NSW = 0 write system.json file for database crawler """ d = {} for cal in self.cal_objs: for i, jdir in enumerate(cal.old_job_dir_list): job_dir = self.job_dir + os.sep \ + jdir.replace(os.sep, '_').replace('.', '_') + \ os.sep + 'STATIC' cal.incar = Incar.from_file(jdir + os.sep + 'INCAR') cal.incar['EDIFF'] = '1E-6' cal.incar['NSW'] = 0 cal.potcar = Potcar.from_file(jdir + os.sep + 'POTCAR') cal.kpoints = Kpoints.from_file(jdir + os.sep + 'KPOINTS') contcar_file = jdir + os.sep + 'CONTCAR' if os.path.isfile(contcar_file): cal.poscar = Poscar.from_file(contcar_file) if cal in self.cal_slabs or cal in self.cal_interfaces: try: d['hkl'] = cal.system['hkl'] except: logger.critical("""the calibrate object doesnt have a system set for calibrating""") if cal in self.cal_interfaces: try: d['ligand'] = cal.system['ligand']['name'] except: logger.critical("""the calibrate object doesnt have a system set for calibrating""") if not os.path.exists(job_dir): os.makedirs(job_dir) if d: with open(job_dir + os.sep + 'system.json', 'w') as f: json.dump(d, f) cal.add_job(job_dir=job_dir) else: logger.critical("""CONTCAR doesnt exist. Setting up job using input set in the old calibration directory""") cal.poscar = Poscar.from_file(jdir + os.sep + 'POSCAR') cal.add_job(job_dir=job_dir)
def setup(self): """ setup static jobs for the calibrate objects copies CONTCAR to POSCAR sets NSW = 0 write system.json file for database crawler """ d = {} for cal in self.cal_objs: for i, jdir in enumerate(cal.old_job_dir_list): job_dir = self.job_dir + os.sep \ + jdir.replace(os.sep, '_').replace('.', '_') + \ os.sep + 'STATIC' cal.incar = Incar.from_file(jdir + os.sep + 'INCAR') cal.incar['EDIFF'] = '1E-6' cal.incar['NSW'] = 0 cal.potcar = Potcar.from_file(jdir + os.sep + 'POTCAR') cal.kpoints = Kpoints.from_file(jdir + os.sep + 'KPOINTS') contcar_file = jdir + os.sep + 'CONTCAR' if os.path.isfile(contcar_file): cal.poscar = Poscar.from_file(contcar_file) if cal in self.cal_slabs or cal in self.cal_interfaces: try: d['hkl'] = cal.system['hkl'] except: logger.critical("""the calibrate object doesnt have a system set for calibrating""") if cal in self.cal_interfaces: try: d['ligand'] = cal.system['ligand']['name'] except: logger.critical("""the calibrate object doesnt have a system set for calibrating""") if not os.path.exists(job_dir): os.makedirs(job_dir) if d: with open(job_dir + os.sep + 'system.json', 'w') as f: json.dump(d, f) cal.add_job(job_dir=job_dir) else: logger.critical("""CONTCAR doesnt exist. Setting up job using input set in the old calibration directory""") cal.poscar = Poscar.from_file(jdir + os.sep + 'POSCAR') cal.add_job(job_dir=job_dir)
def test_init(self): prev_run = os.path.join(test_dir, "relaxation") vis = MPNonSCFSet.from_prev_calc( prev_calc_dir=prev_run, mode="Line", copy_chgcar=False) self.assertEqual(vis.incar["NSW"], 0) # Check that the ENCUT has been inherited. self.assertEqual(vis.incar["ENCUT"], 600) self.assertEqual(vis.kpoints.style, Kpoints.supported_modes.Reciprocal) # Check as from dict. vis = MPNonSCFSet.from_dict(vis.as_dict()) self.assertEqual(vis.incar["NSW"], 0) # Check that the ENCUT has been inherited. self.assertEqual(vis.incar["ENCUT"], 600) self.assertEqual(vis.kpoints.style, Kpoints.supported_modes.Reciprocal) vis.write_input(self.tmp) self.assertFalse(os.path.exists(os.path.join(self.tmp, "CHGCAR"))) vis = MPNonSCFSet.from_prev_calc(prev_calc_dir=prev_run, mode="Line", copy_chgcar=True) vis.write_input(self.tmp) self.assertTrue(os.path.exists(os.path.join(self.tmp, "CHGCAR"))) # Code below is just to make sure that the parameters are the same # between the old MPStaticVaspInputSet and the new MPStaticSet. # TODO: Delete code below in future. MPNonSCFVaspInputSet.from_previous_vasp_run( previous_vasp_dir=prev_run, output_dir=self.tmp, mode="Line") incar = Incar.from_file(os.path.join(self.tmp, "INCAR")) for k, v1 in vis.incar.items(): v2 = incar.get(k) try: v1 = v1.upper() v2 = v2.upper() except: # Convert strings to upper case for comparison. Ignore other # types. pass self.assertEqual(v1, v2, str(v1)+str(v2)) kpoints = Kpoints.from_file(os.path.join(self.tmp, "KPOINTS")) self.assertEqual(kpoints.style, vis.kpoints.style) self.assertArrayAlmostEqual(kpoints.kpts, vis.kpoints.kpts)
def nkp(directory): """ Args: directory: Returns: """ # TODO Seems to fail. Could be related to the fact that the symmetry # tolerances are different. input_dir = os.path.abspath(directory) structure = Structure.from_file(os.path.join(input_dir, "POSCAR")) # incar = Incar.from_file(os.path.join(directory, "INCAR")) # if incar.get("MAGMOM", None) is not None: # structure.add_site_property(("magmom"), incar.get("MAGMOM", None)) kpoints = Kpoints.from_file(os.path.join(input_dir, "KPOINTS")) print("Number of irreducible kpoints = " + str(find_irr_kpoints(structure, kpoints)))
def test_write_inputset(self): name = 'Test' incar = Incar.from_file(TEST_STEP1 + os.sep + 'INCAR') kpoints = Kpoints.from_file(TEST_STEP1 + os.sep + 'KPOINTS') poscar = Poscar.from_file(TEST_STEP1 + os.sep + 'POSCAR') potcar = TEST_STEP1 + os.sep + 'DUMMY_POTSPEC' #potcar = #Potcar.from_dict({'@class': 'Potcar', 'functional': 'PBE',\ # 'symbols': ['Al'], '@module': 'pymatgen.io.vasp.inputs'}) reuse_path = [TEST_STEP1 + os.sep + 'COPY_FILE'] print(reuse_path) mvis = MPINTVaspInputSet(name, incar, poscar, potcar, kpoints, reuse_path=reuse_path, test=True) mvis.write_input(job_dir=TEST_STEP2) self.assertCountEqual(os.listdir(TEST_STEP2), ['INCAR', 'KPOINTS', 'POSCAR', 'COPY_FILE']) cleanup = [ os.remove(TEST_STEP2 + os.sep + f) for f in os.listdir(TEST_STEP2) ]
def __init__(self, structure, prev_incar=None, prev_kpoints=None, lepsilon=False, lcalcpol=False, grid_density=2000, **kwargs): super(PRLRoughStaticSet, self).__init__(structure, PRLRoughStaticSet.CONFIG, **kwargs) if isinstance(prev_incar, six.string_types): prev_incar = Incar.from_file(prev_incar) if isinstance(prev_kpoints, six.string_types): prev_kpoints = Kpoints.from_file(prev_kpoints) self.prev_incar = prev_incar self.prev_kpoints = prev_kpoints self.grid_density = grid_density self.structure = structure self.kwargs = kwargs self.lepsilon = lepsilon self.lcalcpol = lcalcpol
def kpar(directory, max_kpar, add_kpar): """ :return: """ input_dir = os.path.abspath(directory) structure = Structure.from_file(os.path.join(input_dir, "POSCAR")) kpoints = Kpoints.from_file(os.path.join(input_dir, "KPOINTS")) suggested_kpar = str(find_suitable_kpar(structure, kpoints, max_kpar)) print("Suggested KPAR based on divisors of the number of kpoints = " + suggested_kpar) if add_kpar: print("Adding KPAR tag to INCAR file.") try: incar = Incar.from_file(os.path.join(directory, "INCAR")) except FileNotFoundError: raise FileNotFoundError("The INCAR file is not found in the " "directory.") incar["KPAR"] = suggested_kpar incar.write_file(os.path.join(directory, "INCAR"))
def run(self): """ Perform the actual VASP run. Returns: (subprocess.Popen) Used for monitoring. """ cmd = list(self.vasp_cmd) if self.auto_gamma: kpts = Kpoints.from_file("KPOINTS") if kpts.style == Kpoints.supported_modes.Gamma \ and tuple(kpts.kpts[0]) == (1, 1, 1): if self.gamma_vasp_cmd is not None and which( self.gamma_vasp_cmd[-1]): cmd = self.gamma_vasp_cmd elif which(cmd[-1] + ".gamma"): cmd[-1] += ".gamma" logger.info("Running {}".format(" ".join(cmd))) with open(self.output_file, 'w') as f_std, \ open(self.stderr_file, "w", buffering=1) as f_err: # Use line buffering for stderr p = subprocess.Popen(cmd, stdout=f_std, stderr=f_err) return p
def test_init(self): filepath = PymatgenTest.TEST_FILES_DIR / "KPOINTS.auto" kpoints = Kpoints.from_file(filepath) self.assertEqual(kpoints.kpts, [[10]], "Wrong kpoint lattice read") filepath = PymatgenTest.TEST_FILES_DIR / "KPOINTS.cartesian" kpoints = Kpoints.from_file(filepath) self.assertEqual( kpoints.kpts, [[0.25, 0, 0], [0, 0.25, 0], [0, 0, 0.25]], "Wrong kpoint lattice read", ) self.assertEqual(kpoints.kpts_shift, [0.5, 0.5, 0.5], "Wrong kpoint shift read") filepath = PymatgenTest.TEST_FILES_DIR / "KPOINTS" kpoints = Kpoints.from_file(filepath) self.kpoints = kpoints self.assertEqual(kpoints.kpts, [[2, 4, 6]]) filepath = PymatgenTest.TEST_FILES_DIR / "KPOINTS.band" kpoints = Kpoints.from_file(filepath) self.assertIsNotNone(kpoints.labels) self.assertEqual(kpoints.style, Kpoints.supported_modes.Line_mode) kpoints_str = str(kpoints) self.assertEqual(kpoints_str.split("\n")[3], "Reciprocal") filepath = PymatgenTest.TEST_FILES_DIR / "KPOINTS.explicit" kpoints = Kpoints.from_file(filepath) self.assertIsNotNone(kpoints.kpts_weights) self.assertEqual( str(kpoints).strip(), """Example file 4 Cartesian 0.0 0.0 0.0 1 None 0.0 0.0 0.5 1 None 0.0 0.5 0.5 2 None 0.5 0.5 0.5 4 None""", ) filepath = PymatgenTest.TEST_FILES_DIR / "KPOINTS.explicit_tet" kpoints = Kpoints.from_file(filepath) self.assertEqual(kpoints.tet_connections, [(6, [1, 2, 3, 4])])
def test_init(self): filepath = os.path.join(test_dir, 'KPOINTS.auto') kpoints = Kpoints.from_file(filepath) self.assertEqual(kpoints.kpts, [[10]], "Wrong kpoint lattice read") filepath = os.path.join(test_dir, 'KPOINTS.cartesian') kpoints = Kpoints.from_file(filepath) self.assertEqual(kpoints.kpts, [[0.25, 0, 0], [0, 0.25, 0], [0, 0, 0.25]], "Wrong kpoint lattice read") self.assertEqual(kpoints.kpts_shift, [0.5, 0.5, 0.5], "Wrong kpoint shift read") filepath = os.path.join(test_dir, 'KPOINTS') kpoints = Kpoints.from_file(filepath) self.kpoints = kpoints self.assertEqual(kpoints.kpts, [[2, 4, 6]]) filepath = os.path.join(test_dir, 'KPOINTS.band') kpoints = Kpoints.from_file(filepath) self.assertIsNotNone(kpoints.labels) self.assertEqual(kpoints.style, Kpoints.supported_modes.Line_mode) kpoints_str = str(kpoints) self.assertEqual(kpoints_str.split("\n")[3], "Reciprocal") filepath = os.path.join(test_dir, 'KPOINTS.explicit') kpoints = Kpoints.from_file(filepath) self.assertIsNotNone(kpoints.kpts_weights) self.assertEqual(str(kpoints).strip(), """Example file 4 Cartesian 0.0 0.0 0.0 1 None 0.0 0.0 0.5 1 None 0.0 0.5 0.5 2 None 0.5 0.5 0.5 4 None""") filepath = os.path.join(test_dir, 'KPOINTS.explicit_tet') kpoints = Kpoints.from_file(filepath) self.assertEqual(kpoints.tet_connections, [(6, [1, 2, 3, 4])])
def test_init(self): filepath = os.path.join(test_dir, 'KPOINTS.auto') kpoints = Kpoints.from_file(filepath) self.assertEqual(kpoints.kpts, [[10]], "Wrong kpoint lattice read") filepath = os.path.join(test_dir, 'KPOINTS.cartesian') kpoints = Kpoints.from_file(filepath) self.assertEqual(kpoints.kpts, [[0.25, 0, 0], [0, 0.25, 0], [0, 0, 0.25]], "Wrong kpoint lattice read") self.assertEqual(kpoints.kpts_shift, [0.5, 0.5, 0.5], "Wrong kpoint shift read") filepath = os.path.join(test_dir, 'KPOINTS') kpoints = Kpoints.from_file(filepath) self.assertEqual(kpoints.kpts, [[2, 4, 6]]) filepath = os.path.join(test_dir, 'KPOINTS.band') kpoints = Kpoints.from_file(filepath) self.assertIsNotNone(kpoints.labels) self.assertEqual(kpoints.style, "Line_mode") kpoints_str = str(kpoints) self.assertEqual(kpoints_str.split("\n")[3], "Reciprocal") filepath = os.path.join(test_dir, 'KPOINTS.explicit') kpoints = Kpoints.from_file(filepath) self.assertIsNotNone(kpoints.kpts_weights) self.assertEqual(str(kpoints).strip(), """Example file 4 Cartesian 0.0 0.0 0.0 1 None 0.0 0.0 0.5 1 None 0.0 0.5 0.5 2 None 0.5 0.5 0.5 4 None""") filepath = os.path.join(test_dir, 'KPOINTS.explicit_tet') kpoints = Kpoints.from_file(filepath) self.assertEqual(kpoints.tet_connections, [(6, [1, 2, 3, 4])])
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 ): r""" 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 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 )
for idx in range(num_ini, num_fin): formula = df['formula'][idx] try: if os.path.exists(os.getcwd() + '/%03d_%s/2nd/surface_np/cont/' % (idx + 1.0, formula)): file_path = ('%03d_%s/2nd/surface_np/cont/') % (idx + 1.0, formula) f.writelines('(Note) %03d_%s : spin-restricted calc. was initially performed\n' % (idx + 1.0, formula)) elif os.path.exists(os.getcwd() + '/%03d_%s/2nd/surface/2nd/' % (idx + 1.0, formula)): file_path = ('%03d_%s/2nd/surface/2nd/') % (idx + 1.0, formula) else: file_path = '' f.writelines('file path was not properly assigned!\n') print(file_path) slab = read_vasp(file_path + 'CONTCAR') KPOINTS = Kpoints.from_file(file_path + 'KPOINTS') potcar_ori = Potcar.from_file(file_path + 'POTCAR') v = Vasprun(file_path + 'vasprun.xml') # print('#'*50," ",v.converged) f.writelines('(File_path) %s\n' % file_path) f.writelines('%03d_%s surface - Electronic & ionic converged? %s\n' % (idx + 1.0, formula, v.converged)) # view(slab) z_param = slab.get_cell_lengths_and_angles()[2] metal_idx_list = [] for atom in slab: if atom.symbol != 'O' and atom.position[2]/z_param > 0.29:
def setup_poscar_jobs(self, scale_list=None, poscar_list=None): """ for scaling the latice vectors of the original structure, scale_list is volume scaling factor list """ if scale_list: for scale in scale_list: self.set_poscar(scale=scale) self.set_potcar() if not self.is_matrix: job_dir = self.job_dir + os.sep + 'POS' + \ os.sep + 'VOLUME_' + str(scale) self.add_job(name=job_dir, job_dir=job_dir) elif poscar_list: for pos in poscar_list: # if it is a twod_database run or any general standard database run, # the incar, kpoints and potcar follow a standard input set # which will be activated by the twod_database tag set to true # NOTE: this implementation means that the first turn_knobs tag # needs to be the poscar objects list # the database tag will be set to the name of the yaml file with the # standard input deck definition for that database # this incar dict provided as the init can be general format # based on the chosen functional, cutoff # so self.incar is a vdW incar for re-relaxation in vdW, gga for every # other calculation or LDA+U for LSDA+U calculations incar_dict = self.incar.as_dict() if self.reuse: # if this is a true list minimally, ['CONTCAR'] # it is to be ensured that the poscar list is a # list of paths as opposed to list of poscar objects by the turn knobs # values # Here pos is the path and r in each self.reuse is the name of the file(s) # to be reused # in a reuse calculation the following are possible: # update incar (Solvation calculations) or reset incar (HSE calculations) # reset kpoints file with IBZKPT # copy a CHGCAR or WAVECAR or both perhaps try: # first setup of POSCAR initial, INCAR, KPOINTS poscar = Poscar.from_file(pos + os.sep + 'CONTCAR') self.logger.info('Read previous relaxed CONTCAR file from {}'. format(pos)) # check if it is KPOINTS altering job like HSE if self.Grid_type == 'hse_bands_2D_prep': # HSE prep calcualtions # reset the INCAR file with a magmom only if exists try: incar_dict = { 'MAGMOM': get_magmom_string(poscar)} except: incar_dict = {} incar_dict = get_2D_incar_hse_prep(incar_dict) self.set_kpoints(poscar=poscar) self.logger.info( 'updated input set for HSE 2D prep calcaultion') elif self.Grid_type == 'hse_bands_2D': # HSE calculation # reset the incar and kpoints file builds # on the preceding calculations (prep calculation) # IBZKPT try: incar_dict = { 'MAGMOM': get_magmom_string(poscar)} except: incar_dict = {} incar_dict = get_2D_incar_hse(incar_dict) self.set_kpoints(poscar=poscar, ibzkpth=pos + os.sep + 'IBZKPT') self.logger.info('updated input set for HSE calcaultion\ using IBZKPT from {0}'.format(pos + os.sep + 'IBZKPT')) elif self.Grid_type == 'hse_bands': # general HSE bands pass elif self.Grid_type == 'Finer_G_Mesh': self.logger.info('updating to Finer G Mesh') kpoint = Kpoints.from_file(pos+os.sep+'KPOINTS') self.set_kpoints(kpoint=kpoint.kpts[0]) else: # use the same kpoints file and build from the old # incar self.kpoints = Kpoints.from_file( pos + os.sep + 'KPOINTS') # decide on how to use incar, use same one or # update or afresh if self.reuse_incar == 'old': incar_dict = Incar.from_file( pos + os.sep + 'INCAR').as_dict() elif self.reuse_incar == 'update': # way to go for cutoff updates, convergence, etc. # but retain the old functional incar_dict.update(Incar.from_file(pos + os.sep + 'INCAR'). as_dict()) else: # use a fresh incar as specified by the init # way to go for example for LDAU or other # major removals done to INCAR # but always retain the MAGMOM if present old_incar_dict = Incar.from_file( pos + os.sep + 'INCAR').as_dict() if 'MAGMOM' in old_incar_dict.keys(): incar_dict['MAGMOM'] = old_incar_dict[ 'MAGMOM'] else: incar_dict = incar_dict if isinstance(self.reuse, list): reuse_paths = [ pos + os.sep + r for r in self.reuse] self.reuse_paths = reuse_paths # Magnetism use cases, updates to be made to the INCAR (MAE) # and poscar (AFM) # MAE and AFM if self.magnetism == 'MAE': # remove vdW tags for MAE calculations vdW_tags = ('GGA', 'AGGAC', 'LUSE_VDW', 'PARAM1', 'PARAM2') for key in vdW_tags: if key in incar_dict: del incar_dict[key] self.logger.info( 'updating input set for MAE calculation') self.mag_init = Outcar( pos + os.sep + 'OUTCAR').total_mag nbands = 2 * \ Vasprun(pos + os.sep + 'vasprun.xml').parameters['NBANDS'] # u_value = Vasprun(pos+os.sep+'vasprun.xml').incar['LDAUU'] # u_value = 4.0 self.logger.info( "updating mag mom with value {0}".format(self.mag_init)) self.logger.info( "updating NBANDS with {0}".format(nbands)) incar_dict.update({'NBANDS': nbands, 'LSORBIT': True, 'EDIFF': 1e-08, 'ICHARG': 11, 'LMAXMIX': 4, 'LCHARG': False, 'ISYM': 0, 'NSW': 0, 'ISPIN': 2, 'IBRION': -1, 'LORBIT': 11, 'MAGMOM': get_magmom_mae(poscar, self.mag_init) }) # incar_dict.update({'LDAUU': u_value}) elif self.magnetism == 'AFM': self.logger.info( 'updating INCAR and POSCAR for AFM calculation') afm, poscar = get_magmom_afm(poscar, self.database) incar_dict.update({'MAGMOM': afm}) except: # check what to do if the previous calculation being reused is not # actuall done .. system exit or adopt a user override # with POSCAR self.logger.warn( 'Empty relaxed CONTCAR file .. Probably job not done') if not self.reuse_override: self.logger.warn( 'You can set reuse_override to continue with POSCAR file, exiting now ..') sys.exit(0) else: self.logger.info('Using old Poscar for rerun') poscar = Poscar.from_file(pos + os.sep + 'POSCAR') # case for non - reuse else: poscar = pos # temporary: magnetism only set if twod flag is activated if self.database == 'twod': incar_dict.update( {'MAGMOM': get_magmom_string(poscar)}) self.set_kpoints(poscar=poscar) self.incar = Incar.from_dict(incar_dict) self.set_poscar(poscar=poscar) self.set_potcar() if not self.is_matrix: job_dir = self.job_dir + os.sep + 'POS' + \ os.sep + self.val_to_name(poscar) self.add_job(name=job_dir, job_dir=job_dir)
def __init__(self, filenames=".", vasprun='vasprun.xml', Kpointsfile='KPOINTS'): warnings.warn( 'Make sure all relevant FATBAND files were generated and read in!') warnings.warn('Use Lobster 3.2.0 or newer for fatband calculations!') VASPRUN = Vasprun(filename=vasprun, ionic_step_skip=None, ionic_step_offset=0, parse_dos=True, parse_eigen=False, parse_projected_eigen=False, parse_potcar_file=False, occu_tol=1e-8, exception_on_bad_xml=True) self.structure = VASPRUN.final_structure self.lattice = self.structure.lattice.reciprocal_lattice self.efermi = VASPRUN.efermi kpoints_object = Kpoints.from_file(Kpointsfile) atomtype = [] atomnames = [] orbital_names = [] if type(filenames) is not type([]) or filenames is None: filenames_new = [] if filenames is None: filenames = '.' for file in os.listdir(filenames): if fnmatch.fnmatch(file, 'FATBAND_*.lobster'): filenames_new.append(os.path.join(filenames, file)) filenames = filenames_new if (len(filenames)) == 0: raise ValueError("No FATBAND files in folder or given") for ifilename, filename in enumerate(filenames): with zopen(filename, "rt") as f: contents = f.read().split("\n") # TODO: could be replaced for future versions of Lobster, get atomname from filename atomnames.append( os.path.split(filename)[1].split('_')[1].capitalize()) parameters = contents[0].split() atomtype.append(re.split(r"[0-9]+", parameters[3])[0].capitalize()) orbital_names.append(parameters[4]) # get atomtype orbital dict atom_orbital_dict = {} for iatom, atom in enumerate(atomnames): if atom not in atom_orbital_dict: atom_orbital_dict[atom] = [] atom_orbital_dict[atom].append(orbital_names[iatom]) # test if there are the same orbitals twice or if two different formats were used or if all necessary orbitals are there for key, items in atom_orbital_dict.items(): if len(set(items)) != len(items): raise (ValueError( "The are two FATBAND files for the same atom and orbital. The program will stop." )) split = [] for item in items: split.append(item.split("_")[0]) for orb, number in collections.Counter(split).items(): if number != 1 and number != 3 and number != 5 and number != 7: raise (ValueError( "Make sure all relevant orbitals were generated and that no duplicates (2p and 2p_x) are present" )) kpoints_array = [] for ifilename, filename in enumerate(filenames): with zopen(filename, "rt") as f: contents = f.read().split("\n") if ifilename == 0: self.nbands = int(parameters[6]) self.number_kpts = kpoints_object.num_kpts - int( contents[1].split()[2]) + 1 if len(contents[1:]) == self.nbands + 2: self.is_spinpolarized = False elif len(contents[1:]) == self.nbands * 2 + 2: self.is_spinpolarized = True else: linenumbers = [] for iline, line in enumerate(contents[1:self.nbands * 2 + 4]): # print(line) # if line in ['\n', '\r\n']: # linenumbers.append(iline) if line.split()[0] == '#': linenumbers.append(iline) if ifilename == 0: if len(linenumbers) == 2: self.is_spinpolarized = True else: self.is_spinpolarized = False if ifilename == 0: eigenvals = {} eigenvals[Spin.up] = [[ collections.defaultdict(float) for i in range(self.number_kpts) ] for j in range(self.nbands)] if self.is_spinpolarized: eigenvals[Spin.down] = [[ collections.defaultdict(float) for i in range(self.number_kpts) ] for j in range(self.nbands)] p_eigenvals = {} p_eigenvals[Spin.up] = [[{ str(e): { str(orb): collections.defaultdict(float) for orb in atom_orbital_dict[e] } for e in atomnames } for i in range(self.number_kpts)] for j in range(self.nbands)] if self.is_spinpolarized: p_eigenvals[Spin.down] = [[{ str(e): { str(orb): collections.defaultdict(float) for orb in atom_orbital_dict[e] } for e in atomnames } for i in range(self.number_kpts)] for j in range(self.nbands)] ikpoint = -1 for iline, line in enumerate(contents[1:-1]): if line.split()[0] == '#': Kpointnumber = int(line.split()[2]) KPOINT = np.array([ float(line.split()[4]), float(line.split()[5]), float(line.split()[6]) ]) if ifilename == 0: kpoints_array.append(KPOINT) linenumber = 0 iband = 0 ikpoint += 1 if linenumber == self.nbands: iband = 0 if line.split()[0] != '#': if linenumber < self.nbands: if ifilename == 0: eigenvals[Spin.up][iband][ikpoint] = float( line.split()[1]) + self.efermi p_eigenvals[Spin.up][iband][ikpoint][atomnames[ ifilename]][orbital_names[ifilename]] = float( line.split()[2]) if linenumber >= self.nbands and self.is_spinpolarized: # print(line.split()) # print(iband) if ifilename == 0: eigenvals[Spin.down][iband][ikpoint] = float( line.split()[1]) + self.efermi p_eigenvals[Spin.down][iband][ikpoint][atomnames[ ifilename]][orbital_names[ifilename]] = float( line.split()[2]) linenumber += 1 iband += 1 self.kpoints_array = kpoints_array self.eigenvals = eigenvals self.p_eigenvals = p_eigenvals label_dict = {} for ilabel, label in enumerate( kpoints_object.labels[-self.number_kpts:], start=0): if label is not None: label_dict[label] = kpoints_array[ilabel] self.label_dict = label_dict
def test_style_setter(self): filepath = os.path.join(test_dir, 'KPOINTS') kpoints = Kpoints.from_file(filepath) self.assertEqual(kpoints.style, Kpoints.supported_modes.Monkhorst) kpoints.style = "G" self.assertEqual(kpoints.style, Kpoints.supported_modes.Gamma)
def double_relaxation_run( cls, vasp_cmd, auto_npar=True, ediffg=-0.05, half_kpts_first_relax=False, auto_continue=False, ): """ Returns a list of two jobs corresponding to an AFLOW style double relaxation run. 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. 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. Returns: List of two jobs corresponding to an AFLOW style run. """ incar_update = {"ISTART": 1} if ediffg: incar_update["EDIFFG"] = ediffg settings_overide_1 = None settings_overide_2 = [ {"dict": "INCAR", "action": {"_set": incar_update}}, {"file": "CONTCAR", "action": {"_file_copy": {"dest": "POSCAR"}}}, ] 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() # lattice vectors with length < 8 will get >1 KPOINT kpts.kpts = ( np.round(np.maximum(np.array(kpts.kpts) / 2, 1)).astype(int).tolist() ) low_kpts_dict = kpts.as_dict() settings_overide_1 = [ {"dict": "KPOINTS", "action": {"_set": low_kpts_dict}} ] settings_overide_2.append( {"dict": "KPOINTS", "action": {"_set": orig_kpts_dict}} ) return [ VaspJob( vasp_cmd, final=False, suffix=".relax1", auto_npar=auto_npar, auto_continue=auto_continue, settings_override=settings_overide_1, ), VaspJob( vasp_cmd, final=True, backup=False, suffix=".relax2", auto_npar=auto_npar, auto_continue=auto_continue, settings_override=settings_overide_2, ), ]
def post_process(self, dir_name, d): """ Post-processing for various files other than the vasprun.xml and OUTCAR. Looks for files: transformations.json and custodian.json. Modify this if other output files need to be processed. Args: dir_name: The dir_name. d: Current doc generated. """ logger.info("Post-processing dir:{}".format(dir_name)) fullpath = os.path.abspath(dir_name) # VASP input generated by pymatgen's alchemy has a transformations.json file that tracks # the origin of a particular structure. If such a file is found, it is inserted into the # task doc as d["transformations"] transformations = {} filenames = glob.glob(os.path.join(fullpath, "transformations.json*")) if len(filenames) >= 1: with zopen(filenames[0], "rt") as f: transformations = json.load(f) try: m = re.match("(\d+)-ICSD", transformations["history"][0]["source"]) if m: d["icsd_id"] = int(m.group(1)) except Exception as ex: logger.warning("Cannot parse ICSD from transformations file.") pass else: logger.warning("Transformations file does not exist.") other_parameters = transformations.get("other_parameters") new_tags = None if other_parameters: # We don't want to leave tags or authors in the # transformations file because they'd be copied into # every structure generated after this one. new_tags = other_parameters.pop("tags", None) new_author = other_parameters.pop("author", None) if new_author: d["author"] = new_author if not other_parameters: # if dict is now empty remove it transformations.pop("other_parameters") d["transformations"] = transformations # Calculations done using custodian has a custodian.json, # which tracks the jobs performed and any errors detected and fixed. # This is useful for tracking what has actually be done to get a # result. If such a file is found, it is inserted into the task doc # as d["custodian"] filenames = glob.glob(os.path.join(fullpath, "custodian.json*")) if len(filenames) >= 1: with zopen(filenames[0], "rt") as f: d["custodian"] = json.load(f) # Convert to full uri path. if self.use_full_uri: d["dir_name"] = get_uri(dir_name) if new_tags: d["tags"] = new_tags # Calculations using custodian generate a *.orig file for the inputs # This is useful to know how the calculation originally started # if such files are found they are inserted into orig_inputs filenames = glob.glob(os.path.join(fullpath, "*.orig*")) if len(filenames) >= 1: d["orig_inputs"] = {} for f in filenames: if "INCAR.orig" in f: d["orig_inputs"]["incar"] = Incar.from_file(f).as_dict() if "POTCAR.orig" in f: d["orig_inputs"]["potcar"] = Potcar.from_file(f).as_dict() if "KPOINTS.orig" in f: d["orig_inputs"]["kpoints"] = Kpoints.from_file(f).as_dict() if "POSCAR.orig" in f: d["orig_inputs"]["poscar"] = Poscar.from_file(f).as_dict() logger.info("Post-processed " + fullpath)
from pymatgen.io.vasp.inputs import Kpoints, Poscar, Potcar, Incar from pymatgen.core import Structure from pymatgen.symmetry.analyzer import SpacegroupAnalyzer from pymatgen.analysis.structure_matcher import StructureMatcher import sys import os from shutil import copytree, copyfileobj, copy sm = StructureMatcher() dir_path = os.path.dirname(os.path.realpath(__file__)) user_directory = sys.argv[1] user_structure = Structure.from_file(sys.argv[1] + "/POSCAR") user_incar = Incar.from_file(sys.argv[1] + "/INCAR") user_kpoints = Kpoints.from_file(sys.argv[1] + "/KPOINTS") data_directory = "{}/fake_vasp_data".format(dir_path) structure_matched = False KPOINTS_matched = None INCAR_matched = None for path, dirs, files in os.walk(data_directory): for directory in dirs: INCAR = Incar.from_file(os.path.join(path, directory) + "/INCAR") structure = Structure.from_file( os.path.join(path, directory) + "/POSCAR") KPOINTS = Kpoints.from_file(os.path.join(path, directory) + "/KPOINTS") s1 = SpacegroupAnalyzer( user_structure).get_primitive_standard_structure() s2 = SpacegroupAnalyzer(structure).get_primitive_standard_structure()
tot_num = zwitter_AA.get_global_number_of_atoms() x_data = [] z_data = [] for i in range(tot_num): x_data.append(zwitter_AA[i].x) z_data.append(zwitter_AA[i].z) zwitter_temp = zwitter_AA # view(zwitter_temp) # count = 0 INCAR = Incar.from_file('INCAR') KPOINTS = Kpoints.from_file('KPOINTS') idx_list = [] scaled_positions = zwitter_temp.get_scaled_positions() for idx in range(tot_num): if scaled_positions[idx][1] > 0.35 and scaled_positions[idx][1] < 0.65: idx_list.append(idx) print('number of atoms in top layer = ',len(idx_list)) a1 = zwitter_AA.cell[0][0] / cell_params[0] a2 = zwitter_AA.cell[0][1] / cell_params[0] a3 = zwitter_AA.cell[0][2] / cell_params[0] print('cell vector A: %4.5f %4.5f %4.5f ' % (a1,a2,a3))
current_step_number = int(current_step_dir_name.split('-')[0]) list_dir = glob('../*') for dir in list_dir: # finding next step directory looking at first number in directory dir_step_number = int(os.path.basename(dir).split('-')[0]) if dir_step_number == current_step_number + 1 : next_step_number = current_step_number + 1 next_step_dir = dir found_next_step = True break # if a next step directory has been found proceed with next calculation submission if found_next_step: kpoints_current_step =Kpoints.from_file('KPOINTS').as_dict() kpoints_next_step = Kpoints.from_file(next_step_dir + '/KPOINTS').as_dict() # if KPOINTS of current and next step are the same copy WAVECAR and CHGCAR if kpoints_current_step == kpoints_next_step: copyfile('WAVECAR', next_step_dir + '/WAVECAR') copyfile('CHGCAR', next_step_dir + '/CHGCAR') f.write(f'KPOINTS of current and next step are the same: CHGCAR and WAVECAR copied in "{next_step_dir}"'+'\n') # copy CONTCAR of current step in POSCAr of next step copyfile('CONTCAR', next_step_dir + '/POSCAR') f.write(f'CONTCAR copied in POSCAR in "{next_step_dir}"'+'\n') f.write(f'Next step calculation in directory "{next_step_dir}" submitted\n') print(f'Next step calculation in directory "{next_step_dir}" submitted\n') # setting directory of next step as working dir and start calculation
def plot_kp_convergence( directory="../vasp/examples/SiOptb88/", plot=False, filename="." ): """ Plot convergence for k-points data Works only if jobs run through jarvis-tools framework Args: directory: parent directory for job run Returns: matplotlib object, converged k-points value """ x = [] y = [] for a in glob.glob(str(directory) + str("/*.json")): if "MAIN-RELAX" in a: main_kp = str(a.split(".json")[0]) + str("/") + str("KPOINTS") main_kp_obj = Kpoints.from_file(main_kp) [k1, k2, k3] = main_kp_obj.kpts[0] elif "KPOINT" in a: k = int(float(str(a.split("-")[-1]).split(".json")[0])) run = str(a.split(".json")[0]) + str("/") + str("vasprun.xml") vrun = Vasprun(run) kpfile = str(a.split(".json")[0]) + str("/") + str("KPOINTS") contcar = Structure.from_file( (a.split(".json")[0]) + str("/") + str("CONTCAR") ) kpoints = Kpoints.from_file(kpfile) [xx, yy, zz] = kpoints.kpts[0] en = float(vrun.final_energy) # /float(contcar.composition.num_atoms) # en =float(vrun.final_energy)/float(contcar.composition.num_atoms) # print "ENERGYYY,AT",en,float(contcar.composition.num_atoms) x.append(k) y.append(en) order = np.argsort(x) xs = np.array(x)[order] ys = np.array(y)[order] len_xs = len(xs) xs1 = [] ys1 = [] target_ys = ys[-1] # print "target=",target_ys for i, el in enumerate(ys): if el <= (float(target_ys) + 0.002): xs1.append(xs[i]) ys1.append(ys[i]) # print "xs,ys=",xs,ys # print "xs1,ys1=",xs1,ys1 left, bottom, width, height = [0.5, 0.5, 0.35, 0.35] plt = get_publication_quality_plot(14, 10) fig, ax1 = plt.subplots() plt.xlabel("Increment in K point", fontsize=20) plt.ylabel("Energy (eV)", fontsize=20) plt.title( str("Converged at ") + str(k1) + str("x") + str(k2) + str("x") + str(k3) + str(" ") + str("Automatic Mesh ") + str(max(x) - 25), fontsize=14, ) plt.xticks(fontsize=20) plt.yticks(fontsize=20) ax2 = fig.add_axes([left, bottom, width, height]) # ax2.plot(xs1,ys1, '.-',linewidth=2,markersize=10) ax1.plot(xs, ys, "s-", linewidth=2, markersize=10) el_list = sorted(list(contcar.symbol_set)) search = "-".join([item for item in el_list]) # ax1.xlabel('Increment in K point') # print "xs,ys" # print xs # print ys plt.plot(xs1, ys1, ".-", linewidth=2, markersize=10) plt.ylim([float(target_ys) + 0.002, float(target_ys) - 0.002]) ax = plt.gca() ax.get_yaxis().get_major_formatter().set_useOffset(False) filename = str("KDen.png") k_convg = str(xx) + str("x") + str(yy) + str("x") + str(zz) plt.tight_layout() if plot == True: plt.savefig(filename) plt.close() return plt, k_convg
def test_style_setter(self): filepath = self.TEST_FILES_DIR / 'KPOINTS' kpoints = Kpoints.from_file(filepath) self.assertEqual(kpoints.style, Kpoints.supported_modes.Monkhorst) kpoints.style = "G" self.assertEqual(kpoints.style, Kpoints.supported_modes.Gamma)
def test_style_setter(self): filepath = self.TEST_FILES_DIR / 'KPOINTS' kpoints = Kpoints.from_file(filepath) self.assertEqual(kpoints.style, Kpoints.supported_modes.Monkhorst) kpoints.style = "G" self.assertEqual(kpoints.style, Kpoints.supported_modes.Gamma)
def setup(self): """ Performs initial setup for VaspNEBJob, including overriding any settings and backing up. """ neb_dirs = self.neb_dirs if self.backup: # Back up KPOINTS, INCAR, POTCAR for f in VASP_NEB_INPUT_FILES: shutil.copy(f, "{}.orig".format(f)) # Back up POSCARs for path in neb_dirs: poscar = os.path.join(path, "POSCAR") shutil.copy(poscar, "{}.orig".format(poscar)) if self.half_kpts and os.path.exists("KPOINTS"): kpts = Kpoints.from_file("KPOINTS") kpts.kpts = np.maximum(np.array(kpts.kpts) / 2, 1) kpts.kpts = kpts.kpts.astype(int).tolist() if tuple(kpts.kpts[0]) == (1, 1, 1): kpt_dic = kpts.as_dict() kpt_dic["generation_style"] = "Gamma" kpts = Kpoints.from_dict(kpt_dic) kpts.write_file("KPOINTS") if self.auto_npar: try: incar = Incar.from_file("INCAR") import multiprocessing # Try sge environment variable first # (since multiprocessing counts cores on the current # machine only) ncores = os.environ.get("NSLOTS") or multiprocessing.cpu_count() ncores = int(ncores) for npar in range(int(math.sqrt(ncores)), ncores): if ncores % npar == 0: incar["NPAR"] = npar break incar.write_file("INCAR") except Exception: pass if ( self.auto_continue and os.path.exists("STOPCAR") and not os.access("STOPCAR", os.W_OK) ): # Remove STOPCAR os.chmod("STOPCAR", 0o644) os.remove("STOPCAR") # Copy CONTCAR to POSCAR for path in self.neb_sub: contcar = os.path.join(path, "CONTCAR") poscar = os.path.join(path, "POSCAR") shutil.copy(contcar, poscar) if self.settings_override is not None: VaspModder().apply_actions(self.settings_override)