def test_runs_assimilate(self): drone = VaspDrone(runs=["relax1", "relax2"]) doc = drone.assimilate(self.relax2) oszicar2 = Oszicar(os.path.join(self.relax2, "OSZICAR.relax2.gz")) outcar1 = Outcar(os.path.join(self.relax2, "OUTCAR.relax1.gz")) outcar2 = Outcar(os.path.join(self.relax2, "OUTCAR.relax2.gz")) outcar1 = outcar1.as_dict() outcar2 = outcar2.as_dict() run_stats1 = outcar1.pop("run_stats") run_stats2 = outcar2.pop("run_stats") self.assertEqual(len(doc["calcs_reversed"]), 2) self.assertEqual(doc["composition_reduced"], {"Si": 1.0}) self.assertEqual(doc["composition_unit_cell"], {"Si": 2.0}) self.assertAlmostEqual(doc["output"]["energy"], oszicar2.ionic_steps[-1]["E0"]) self.assertEqual(doc["formula_pretty"], "Si") self.assertEqual(doc["formula_anonymous"], "A") self.assertEqual( list(doc["calcs_reversed"][0]["input"].keys()), list(doc["calcs_reversed"][1]["input"].keys()), ) self.assertEqual( list(doc["calcs_reversed"][0]["output"].keys()), list(doc["calcs_reversed"][1]["output"].keys()), ) self.assertEqual( doc["calcs_reversed"][0]["output"]["energy"], doc["output"]["energy"] ) self.assertEqual( doc["run_stats"][doc["calcs_reversed"][0]["task"]["name"]], run_stats2 ) self.assertEqual( doc["run_stats"][doc["calcs_reversed"][1]["task"]["name"]], run_stats1 ) self.assertEqual(doc["calcs_reversed"][0]["output"]["outcar"], outcar2) self.assertEqual(doc["calcs_reversed"][1]["output"]["outcar"], outcar1)
def check(self): try: oszicar = Oszicar(self.output_filename) if oszicar.final_energy > 0: return True except: pass return False
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 prep_ml_formation_energy(fileroot="."): """ writes .poscar and .energy files with index information for use in model training Parameters ---------- """ n = 100 # number of steps to sample i = 0 for a in os.walk("."): directory = a[0] s_extension = "poscar" e_extension = "energy" prefix = "" # prefix for files, e.g. name of structure # e.g. "[root]/[prefix][i].[poscar]" where i=1,2,...,n try: s_list = Xdatcar(directory + "/XDATCAR").structures e_list = [ step["E0"] for step in Oszicar(directory + "/OSZICAR").ionic_steps ] if n < len(s_list) - 1: # the idea here is to obtain a subset of n energies # such that the energies are as evenly-spaced as possible # we do this in energy-space not in relaxation-space # because energies drop fast and then level off idx_to_keep = [] fitting_data = np.array( e_list)[:, np.newaxis] # kmeans expects 2D kmeans_model = KMeans(n_clusters=n) kmeans_model.fit(fitting_data) cluster_centers = sorted( kmeans_model.cluster_centers_.flatten()) for centroid in cluster_centers: closest_idx = np.argmin(np.subtract(e_list, centroid)**2) idx_to_keep.append(closest_idx) idx_to_keep[-1] = len(e_list) - 1 # replace the last idx_list = np.arange(len(s_list)) idx_batched = np.array_split(idx_list[:-1], n) idx_kept = [batch[0] for batch in idx_batched] idx_kept.append(idx_list[-1]) else: idx_kept = np.arange(len(e_list)) for j, idx in enumerate(idx_kept): filestem = str(j) i2 = str(i) s_filename = "{}/{}{}_{}.{}".format(fileroot, prefix, i2, filestem, s_extension) e_filename = "{}/{}{}_{}.{}".format(fileroot, prefix, i2, filestem, e_extension) s_list[idx].to(fmt="poscar", filename=s_filename) with open(e_filename, "w") as f: f.write(str(e_list[idx])) i = i + 1 except: print("noFile")
def prep_ml_formation_energy(calculation, fileroot='.'): os.mkdir('formation_energy') os.chdir('formation_energy') urlo = ('http://2d' + calculation['path'][9:21] + '.org/' + calculation['path'][22:] + '/OSZICAR') fileo = urllib.request.urlopen(urlo) urlx = ('http://2d' + calculation['path'][9:21] + '.org/' + calculation['path'][22:] + '/XDATCAR') filex = urllib.request.urlopen(urlx) with open('OsZICAR', 'a') as oszicar: for line in fileo: decoded_line = line.decode("utf-8") oszicar.write(decoded_line) with open('XdATCAR', 'a') as xdatcar: for line in filex: decoded_line = line.decode("utf-8") xdatcar.write(decoded_line) n = 100 # number of steps to sample s_extension = 'poscar' e_extension = 'energy' prefix = '' # prefix for files, e.g. name of structure # e.g. "[root]/[prefix][i].[poscar]" where i=1,2,...,n s_list = Xdatcar('XdATCAR').structures e_list = [step['E0'] for step in Oszicar('OsZICAR').ionic_steps] if n < len(s_list) - 1: # the idea here is to obtain a subset of n energies # such that the energies are as evenly-spaced as possible # we do this in energy-space not in relaxation-space # because energies drop fast and then level off idx_to_keep = [] fitting_data = np.array(e_list)[:, np.newaxis] # kmeans expects 2D kmeans_model = KMeans(n_clusters=n) kmeans_model.fit(fitting_data) cluster_centers = sorted(kmeans_model.cluster_centers_.flatten()) for centroid in cluster_centers: closest_idx = np.argmin(np.subtract(e_list, centroid)**2) idx_to_keep.append(closest_idx) idx_to_keep[-1] = len(e_list) - 1 # replace the last idx_list = np.arange(len(s_list)) idx_batched = np.array_split(idx_list[:-1], n) idx_kept = [batch[0] for batch in idx_batched] idx_kept.append(idx_list[-1]) else: idx_kept = np.arange(len(e_list)) for j, idx in enumerate(idx_kept): filestem = str(j) s_filename = '{}/{}{}.{}'.format(fileroot, prefix, filestem, s_extension) e_filename = '{}/{}{}.{}'.format(fileroot, prefix, filestem, e_extension) s_list[idx].to(fmt='poscar', filename=s_filename) with open(e_filename, 'w') as f: f.write(str(e_list[idx]))
def check(self): if self.wall_time: run_time = datetime.datetime.now() - self.start_time total_secs = run_time.total_seconds() if not self.electronic_step_stop: try: # Intelligently determine time per ionic step. o = Oszicar("OSZICAR") nsteps = len(o.ionic_steps) time_per_step = total_secs / nsteps except Exception: time_per_step = 0 else: try: # Intelligently determine approximate time per electronic # step. o = Oszicar("OSZICAR") if len(o.ionic_steps) == 0: nsteps = 0 else: nsteps = sum(map(len, o.electronic_steps)) if nsteps > self.prev_check_nscf_steps: steps_time = datetime.datetime.now() - \ self.prev_check_time steps_secs = steps_time.total_seconds() step_timing = self.buffer_time * ceil( (steps_secs / (nsteps - self.prev_check_nscf_steps)) / self.buffer_time) self.electronic_steps_timings.append(step_timing) self.prev_check_nscf_steps = nsteps self.prev_check_time = datetime.datetime.now() time_per_step = max(self.electronic_steps_timings) except Exception as ex: time_per_step = 0 # If the remaining time is less than average time for 3 ionic # steps or buffer_time. time_left = self.wall_time - total_secs if time_left < max(time_per_step * 3, self.buffer_time): return True return False
def check(self): vi = VaspInput.from_directory(".") nelm = vi["INCAR"].get("NELM", 60) try: oszicar = Oszicar(self.output_filename) esteps = oszicar.electronic_steps if len(esteps) > self.nionic_steps: return all([len(e) == nelm for e in esteps[-(self.nionic_steps + 1):-1]]) except: pass return False
def make_energy_mag_yamls(): filename_e = "../mp_atom_energy.yaml" filename_m = "../mp_atom_mag.yaml" try: os.remove(filename_e) except FileNotFoundError: pass try: os.remove(filename_m) except FileNotFoundError: pass energies = [] mags = [] for e in Element: # Z(Pr) = 59, Z(Yb) = 70, Z(Pa) = 91, Z(No) = 102 if 59 <= e.Z <= 70 or 84 <= e.Z: continue if e == Element.Ti: d = "algo_n/Ti_mag2" elif e == Element.La: d = "algo_n/La_mag1" elif str(e) in [ "B", "P", "Ce", "Co", "Fe", "Ni", "Sb", "Si", "Tc", "Th" ]: d = f"algo_n/{e}" else: d = f"algo_d/{e}" o = Oszicar(Path(d) / "OSZICAR") s = str(e) + ':' energies.append(f"{s:<3} {o.final_energy:11.8f}") mags.append(f"{s:<3} {abs(o.ionic_steps[-1]['mag']):5.2f}") Path(filename_e).write_text("\n".join(energies)) Path(filename_m).write_text("\n".join(mags))
def correct(self): backup(VASP_BACKUP_FILES | {self.output_filename}) actions = [] vi = VaspInput.from_directory(".") if self.errors.intersection(["tet", "dentet"]): actions.append({"dict": "INCAR", "action": {"_set": {"ISMEAR": 0}}}) if "inv_rot_mat" in self.errors: actions.append({"dict": "INCAR", "action": {"_set": {"SYMPREC": 1e-8}}}) if "brmix" in self.errors: # If there is not a valid OUTCAR already, increment # error count to 1 to skip first fix if self.error_count['brmix'] == 0: try: assert (Outcar(zpath(os.path.join( os.getcwd(), "OUTCAR"))).is_stopped is False) except: self.error_count['brmix'] += 1 if self.error_count['brmix'] == 0: # Valid OUTCAR - simply rerun the job and increment # error count for next time actions.append({"dict": "INCAR", "action": {"_set": {"ISTART": 1}}}) self.error_count['brmix'] += 1 elif self.error_count['brmix'] == 1: # Use Kerker mixing w/default values for other parameters actions.append({"dict": "INCAR", "action": {"_set": {"IMIX": 1}}}) self.error_count['brmix'] += 1 elif self.error_count['brmix'] == 2 and vi["KPOINTS"].style \ == Kpoints.supported_modes.Gamma: actions.append({"dict": "KPOINTS", "action": {"_set": {"generation_style": "Monkhorst"}}}) actions.append({"dict": "INCAR", "action": {"_unset": {"IMIX": 1}}}) self.error_count['brmix'] += 1 elif self.error_count['brmix'] in [2, 3] and vi["KPOINTS"].style \ == Kpoints.supported_modes.Monkhorst: actions.append({"dict": "KPOINTS", "action": {"_set": {"generation_style": "Gamma"}}}) actions.append({"dict": "INCAR", "action": {"_unset": {"IMIX": 1}}}) self.error_count['brmix'] += 1 if vi["KPOINTS"].num_kpts < 1: all_kpts_even = all([ bool(n % 2 == 0) for n in vi["KPOINTS"].kpts[0] ]) print("all_kpts_even = {}".format(all_kpts_even)) if all_kpts_even: new_kpts = ( tuple(n + 1 for n in vi["KPOINTS"].kpts[0]),) print("new_kpts = {}".format(new_kpts)) actions.append({"dict": "KPOINTS", "action": {"_set": { "kpoints": new_kpts }}}) else: actions.append({"dict": "INCAR", "action": {"_set": {"ISYM": 0}}}) if vi["KPOINTS"].style == Kpoints.supported_modes.Monkhorst: actions.append({"dict": "KPOINTS", "action": { "_set": {"generation_style": "Gamma"}}}) # Based on VASP forum's recommendation, you should delete the # CHGCAR and WAVECAR when dealing with this error. if vi["INCAR"].get("ICHARG", 0) < 10: actions.append({"file": "CHGCAR", "action": { "_file_delete": {'mode': "actual"}}}) actions.append({"file": "WAVECAR", "action": { "_file_delete": {'mode': "actual"}}}) if "zpotrf" in self.errors: # Usually caused by short bond distances. If on the first step, # volume needs to be increased. Otherwise, it was due to a step # being too big and POTIM should be decreased. If a static run # try turning off symmetry. try: oszicar = Oszicar("OSZICAR") nsteps = len(oszicar.ionic_steps) except: nsteps = 0 if nsteps >= 1: potim = float(vi["INCAR"].get("POTIM", 0.5)) / 2.0 actions.append( {"dict": "INCAR", "action": {"_set": {"ISYM": 0, "POTIM": potim}}}) elif vi["INCAR"].get("NSW", 0) == 0 \ or vi["INCAR"].get("ISIF", 0) in range(3): actions.append( {"dict": "INCAR", "action": {"_set": {"ISYM": 0}}}) else: s = vi["POSCAR"].structure s.apply_strain(0.2) actions.append({"dict": "POSCAR", "action": {"_set": {"structure": s.as_dict()}}}) # Based on VASP forum's recommendation, you should delete the # CHGCAR and WAVECAR when dealing with this error. if vi["INCAR"].get("ICHARG", 0) < 10: actions.append({"file": "CHGCAR", "action": {"_file_delete": {'mode': "actual"}}}) actions.append({"file": "WAVECAR", "action": {"_file_delete": {'mode': "actual"}}}) if self.errors.intersection(["subspacematrix", "rspher", "real_optlay", "nicht_konv"]): s = vi["POSCAR"].structure if len(s) < self.natoms_large_cell: actions.append({"dict": "INCAR", "action": {"_set": {"LREAL": False}}}) else: # for large supercell, try an in-between option LREAL = True # prior to LREAL = False if self.error_count['real_optlay'] == 0: # use real space projectors generated by pot actions.append({"dict": "INCAR", "action": {"_set": {"LREAL": True}}}) self.error_count['real_optlay'] += 1 elif self.error_count['real_optlay'] == 1: actions.append({"dict": "INCAR", "action": {"_set": {"LREAL": False}}}) self.error_count['real_optlay'] += 1 if self.errors.intersection(["tetirr", "incorrect_shift"]): if vi["KPOINTS"].style == Kpoints.supported_modes.Monkhorst: actions.append({"dict": "KPOINTS", "action": { "_set": {"generation_style": "Gamma"}}}) if "rot_matrix" in self.errors: if vi["KPOINTS"].style == Kpoints.supported_modes.Monkhorst: actions.append({"dict": "KPOINTS", "action": { "_set": {"generation_style": "Gamma"}}}) else: actions.append({"dict": "INCAR", "action": {"_set": {"ISYM": 0}}}) if "amin" in self.errors: actions.append({"dict": "INCAR", "action": {"_set": {"AMIN": "0.01"}}}) if "triple_product" in self.errors: s = vi["POSCAR"].structure trans = SupercellTransformation(((1, 0, 0), (0, 0, 1), (0, 1, 0))) new_s = trans.apply_transformation(s) actions.append({"dict": "POSCAR", "action": {"_set": {"structure": new_s.as_dict()}}, "transformation": trans.as_dict()}) if "pricel" in self.errors: actions.append({"dict": "INCAR", "action": {"_set": {"SYMPREC": 1e-8, "ISYM": 0}}}) if "brions" in self.errors: potim = float(vi["INCAR"].get("POTIM", 0.5)) + 0.1 actions.append({"dict": "INCAR", "action": {"_set": {"POTIM": potim}}}) if "zbrent" in self.errors: actions.append({"dict": "INCAR", "action": {"_set": {"IBRION": 1}}}) actions.append({"file": "CONTCAR", "action": {"_file_copy": {"dest": "POSCAR"}}}) if "too_few_bands" in self.errors: if "NBANDS" in vi["INCAR"]: nbands = int(vi["INCAR"]["NBANDS"]) else: with open("OUTCAR") as f: for line in f: if "NBANDS" in line: try: d = line.split("=") nbands = int(d[-1].strip()) break except (IndexError, ValueError): pass actions.append({"dict": "INCAR", "action": {"_set": {"NBANDS": int(1.1 * nbands)}}}) if "pssyevx" in self.errors: actions.append({"dict": "INCAR", "action": {"_set": {"ALGO": "Normal"}}}) if "eddrmm" in self.errors: # RMM algorithm is not stable for this calculation if vi["INCAR"].get("ALGO", "Normal") in ["Fast", "VeryFast"]: actions.append({"dict": "INCAR", "action": {"_set": {"ALGO": "Normal"}}}) else: potim = float(vi["INCAR"].get("POTIM", 0.5)) / 2.0 actions.append({"dict": "INCAR", "action": {"_set": {"POTIM": potim}}}) if vi["INCAR"].get("ICHARG", 0) < 10: actions.append({"file": "CHGCAR", "action": {"_file_delete": {'mode': "actual"}}}) actions.append({"file": "WAVECAR", "action": {"_file_delete": {'mode': "actual"}}}) if "edddav" in self.errors: if vi["INCAR"].get("ICHARG", 0) < 10: actions.append({"file": "CHGCAR", "action": {"_file_delete": {'mode': "actual"}}}) actions.append({"dict": "INCAR", "action": {"_set": {"ALGO": "All"}}}) if "grad_not_orth" in self.errors: if vi["INCAR"].get("ISMEAR", 1) < 0: actions.append({"dict": "INCAR", "action": {"_set": {"ISMEAR": "0"}}}) if "zheev" in self.errors: if vi["INCAR"].get("ALGO", "Fast").lower() != "exact": actions.append({"dict": "INCAR", "action": {"_set": {"ALGO": "Exact"}}}) if "elf_kpar" in self.errors: actions.append({"dict": "INCAR", "action": {"_set": {"KPAR": 1}}}) if "rhosyg" in self.errors: if vi["INCAR"].get("SYMPREC", 1e-4) == 1e-4: actions.append({"dict": "INCAR", "action": {"_set": {"ISYM": 0}}}) actions.append({"dict": "INCAR", "action": {"_set": {"SYMPREC": 1e-4}}}) if "posmap" in self.errors: actions.append({"dict": "INCAR", "action": {"_set": {"SYMPREC": 1e-6}}}) VaspModder(vi=vi).apply_actions(actions) return {"errors": list(self.errors), "actions": actions}
def correct(self): backup(VASP_BACKUP_FILES | {self.output_filename}) actions = [] vi = VaspInput.from_directory(".") if self.errors.intersection(["tet", "dentet"]): actions.append({ "dict": "INCAR", "action": { "_set": { "ISMEAR": 0 } } }) if "inv_rot_mat" in self.errors: actions.append({ "dict": "INCAR", "action": { "_set": { "SYMPREC": 1e-8 } } }) if "brmix" in self.errors: if self.error_count['brmix'] == 0 and vi[ "KPOINTS"].style == Kpoints.supported_modes.Gamma: actions.append({ "dict": "KPOINTS", "action": { "_set": { "generation_style": "Monkhorst" } } }) self.error_count['brmix'] += 1 elif self.error_count['brmix'] <= 1 and vi[ "KPOINTS"].style == Kpoints.supported_modes.Monkhorst: actions.append({ "dict": "KPOINTS", "action": { "_set": { "generation_style": "Gamma" } } }) self.error_count['brmix'] += 1 if vi["KPOINTS"].num_kpts < 1: all_kpts_even = all( [bool(n % 2 == 0) for n in vi["KPOINTS"].kpts[0]]) print("all_kpts_even = {}".format(all_kpts_even)) if all_kpts_even: new_kpts = (tuple(n + 1 for n in vi["KPOINTS"].kpts[0]), ) print("new_kpts = {}".format(new_kpts)) actions.append({ "dict": "KPOINTS", "action": { "_set": { "kpoints": new_kpts } } }) else: actions.append({ "dict": "INCAR", "action": { "_set": { "ISYM": 0 } } }) if vi["KPOINTS"].style == Kpoints.supported_modes.Monkhorst: actions.append({ "dict": "KPOINTS", "action": { "_set": { "generation_style": "Gamma" } } }) # Based on VASP forum's recommendation, you should delete the # CHGCAR and WAVECAR when dealing with this error. actions.append({ "file": "CHGCAR", "action": { "_file_delete": { 'mode': "actual" } } }) actions.append({ "file": "WAVECAR", "action": { "_file_delete": { 'mode': "actual" } } }) if "zpotrf" in self.errors: # Usually caused by short bond distances. If on the first step, # volume needs to be increased. Otherwise, it was due to a step # being too big and POTIM should be decreased. try: oszicar = Oszicar("OSZICAR") nsteps = len(oszicar.ionic_steps) except: nsteps = 0 if nsteps >= 1: potim = float(vi["INCAR"].get("POTIM", 0.5)) / 2.0 actions.append({ "dict": "INCAR", "action": { "_set": { "ISYM": 0, "POTIM": potim } } }) else: s = vi["POSCAR"].structure s.apply_strain(0.2) actions.append({ "dict": "POSCAR", "action": { "_set": { "structure": s.as_dict() } } }) # Based on VASP forum's recommendation, you should delete the # CHGCAR and WAVECAR when dealing with this error. actions.append({ "file": "CHGCAR", "action": { "_file_delete": { 'mode': "actual" } } }) actions.append({ "file": "WAVECAR", "action": { "_file_delete": { 'mode': "actual" } } }) if self.errors.intersection( ["subspacematrix", "rspher", "real_optlay"]): actions.append({ "dict": "INCAR", "action": { "_set": { "LREAL": False } } }) if self.errors.intersection(["tetirr", "incorrect_shift"]): if vi["KPOINTS"].style == Kpoints.supported_modes.Monkhorst: actions.append({ "dict": "KPOINTS", "action": { "_set": { "generation_style": "Gamma" } } }) if "rot_matrix" in self.errors: if vi["KPOINTS"].style == Kpoints.supported_modes.Monkhorst: actions.append({ "dict": "KPOINTS", "action": { "_set": { "generation_style": "Gamma" } } }) else: actions.append({ "dict": "INCAR", "action": { "_set": { "ISYM": 0 } } }) if "amin" in self.errors: actions.append({ "dict": "INCAR", "action": { "_set": { "AMIN": "0.01" } } }) if "triple_product" in self.errors: s = vi["POSCAR"].structure trans = SupercellTransformation(((1, 0, 0), (0, 0, 1), (0, 1, 0))) new_s = trans.apply_transformation(s) actions.append({ "dict": "POSCAR", "action": { "_set": { "structure": new_s.as_dict() } }, "transformation": trans.as_dict() }) if "pricel" in self.errors: actions.append({ "dict": "INCAR", "action": { "_set": { "SYMPREC": 1e-8, "ISYM": 0 } } }) if "brions" in self.errors: potim = float(vi["INCAR"].get("POTIM", 0.5)) + 0.1 actions.append({ "dict": "INCAR", "action": { "_set": { "POTIM": potim } } }) if "zbrent" in self.errors: actions.append({ "dict": "INCAR", "action": { "_set": { "IBRION": 1 } } }) if "too_few_bands" in self.errors: if "NBANDS" in vi["INCAR"]: nbands = int(vi["INCAR"]["NBANDS"]) else: with open("OUTCAR") as f: for line in f: if "NBANDS" in line: try: d = line.split("=") nbands = int(d[-1].strip()) break except (IndexError, ValueError): pass actions.append({ "dict": "INCAR", "action": { "_set": { "NBANDS": int(1.1 * nbands) } } }) if "pssyevx" in self.errors: actions.append({ "dict": "INCAR", "action": { "_set": { "ALGO": "Normal" } } }) if "eddrmm" in self.errors: #RMM algorithm is not stable for this calculation if vi["INCAR"].get("ALGO", "Normal") in ["Fast", "VeryFast"]: actions.append({ "dict": "INCAR", "action": { "_set": { "ALGO": "Normal" } } }) else: potim = float(vi["INCAR"].get("POTIM", 0.5)) / 2.0 actions.append({ "dict": "INCAR", "action": { "_set": { "POTIM": potim } } }) actions.append({ "file": "CHGCAR", "action": { "_file_delete": { 'mode': "actual" } } }) actions.append({ "file": "WAVECAR", "action": { "_file_delete": { 'mode': "actual" } } }) if "edddav" in self.errors: actions.append({ "file": "CHGCAR", "action": { "_file_delete": { 'mode': "actual" } } }) actions.append({ "dict": "INCAR", "action": { "_set": { "ALGO": "All" } } }) VaspModder(vi=vi).apply_actions(actions) return {"errors": list(self.errors), "actions": actions}
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
volume_ref = entries[idx]['volume'] * scaling df_bulk.Volume_ref[idx+1] = volume_ref # save conventional unit cell createFolder('results/bulk_models') conv_struc.to(filename = "results/bulk_models/POSCAR_%s" % (formula)) conv_struc.to(filename = "results/bulk_models/%s.cif" % (formula)) """ Import from my results """ file_path = '%03d_%s/2nd/' % (idx + 1.0, formula) try: oszicar = Oszicar(file_path + 'OSZICAR') tot_E = oszicar.ionic_steps[-1]['F'] tot_mag = oszicar.ionic_steps[-1]['mag'] df_bulk.total_E[idx+1] = tot_E df_bulk.tot_mag[idx+1] = tot_mag v = Vasprun(file_path + 'vasprun.xml') volume = v.as_dict()['output']['crystal']['lattice']['volume'] df_bulk.Volume[idx+1] = volume df_bulk.Err_V_percent[idx+1] = (volume_ref - volume) / volume_ref * 100 el = v.as_dict()['elements'] el.remove('O')
df_bulk.Eg_ref[idx+1] = entries[idx]['band_gap'] df_bulk.Theoretical[idx+1] = entries[idx]['theoretical'] volume_ref = entries[idx]['volume'] * scaling df_bulk.Volume_ref[idx+1] = volume_ref # save conventional unit cell createFolder('results/bulk_models') conv_struc.to(filename = "results/bulk_models/POSCAR_%s" % (formula)) conv_struc.to(filename = "results/bulk_models/%s.cif" % (formula)) """ Import from my results """ try: oszicar = Oszicar('%03d_%s/2nd/OSZICAR' % (idx + 1.0, formula)) tot_E = oszicar.ionic_steps[-1]['F'] tot_mag = oszicar.ionic_steps[-1]['mag'] df_bulk.total_E[idx+1] = tot_E df_bulk.tot_mag[idx+1] = tot_mag v = Vasprun('%03d_%s/2nd/vasprun.xml' % (idx + 1.0, formula)) volume = v.as_dict()['output']['crystal']['lattice']['volume'] df_bulk.Volume[idx+1] = volume df_bulk.Err_V_percent[idx+1] = (volume_ref - volume) / volume_ref * 100 el = v.as_dict()['elements'] el.remove('O')
import math from pymatgen import Structure, Element from pymatgen.io.vasp import Oszicar, Xdatcar, Vasprun import os import numpy as np os.chdir('/home/jinho93/interface/lsmo-bto-pt/2.vaccum/baobao/up/again') dat = Xdatcar('XDATCAR') zicar = Oszicar('OSZICAR') vrun = Vasprun('vasprun.xml') energies = zicar.ionic_steps selective = [ r.properties['selective_dynamics'][2] for r in vrun.final_structure.sites ] output = [] ionic = vrun.ionic_steps for s, e, ion in zip(dat.structures, energies, ionic): sr = [] ti = [] z = [] for i in s.sites: if i.specie == Element.O: z.append(i.z) elif i.specie == Element.Ti or i.specie == Element.Ti: ti.append(i.z) elif i.specie is Element.Ba or i.specie == Element.Ba: sr.append(i.z) arr_Sr = [x - y for x, y in zip(sorted(sr[1:]), sorted(z)[2::3])] arr_Ti = [x - y for x, y in zip(sorted(ti), sorted(z)[1::3])] if max(np.array(ion['forces'])[:, 2][selective]) < .2: