def process_bandstructure(self, vrun): vasprun_file = vrun.filename # Band structure parsing logic if str(self.bandstructure_mode).lower() == "auto": # if NSCF calculation if vrun.incar.get("ICHARG", 0) > 10: bs_vrun = BSVasprun(vasprun_file, parse_projected_eigen=True) try: # Try parsing line mode bs = bs_vrun.get_band_structure(line_mode=True) except: # Just treat as a regular calculation bs = bs_vrun.get_band_structure() # else just regular calculation else: bs_vrun = BSVasprun(vasprun_file, parse_projected_eigen=False) bs = bs_vrun.get_band_structure() # only save the bandstructure if not moving ions if vrun.incar.get("NSW", 0) <= 1: return bs.as_dict() # legacy line/True behavior for bandstructure_mode elif self.bandstructure_mode: bs_vrun = BSVasprun(vasprun_file, parse_projected_eigen=True) bs = bs_vrun.get_band_structure( line_mode=(str(self.bandstructure_mode).lower() == "line")) return bs.as_dict() return None
def wave(**kwargs): """Extract wavefunction coefficients from a WAVECAR""" from pymatgen.io.vasp import BSVasprun from amset.constants import defaults from amset.electronic_structure.common import ( get_band_structure, get_ibands, get_zero_weighted_kpoint_indices, ) from amset.tools.common import echo_ibands from amset.wavefunction.io import write_coefficients output = kwargs.pop("output") planewave_cutoff = kwargs.pop("planewave_cutoff") pawpyseed = kwargs.pop("pawpyseed") energy_cutoff = kwargs.pop("energy_cutoff") if not energy_cutoff: energy_cutoff = defaults["energy_cutoff"] if kwargs["directory"]: vasprun_file = Path(kwargs["directory"]) / "vasprun.xml" else: vasprun_file = kwargs["vasprun"] try: vr = BSVasprun(vasprun_file) except FileNotFoundError: vr = BSVasprun(str(vasprun_file) + ".gz") zwk_mode = kwargs.pop("zero_weighted_kpoints") if not zwk_mode: zwk_mode = defaults["zero_weighted_kpoints"] bs = get_band_structure(vr, zero_weighted=zwk_mode) if "bands" in kwargs and kwargs["bands"] is not None: ibands = parse_ibands(kwargs["bands"]) else: ibands = get_ibands(energy_cutoff, bs) ikpoints = get_zero_weighted_kpoint_indices(vr, zwk_mode) click.echo("******* Getting wavefunction coefficients *******\n") echo_ibands(ibands, bs.is_spin_polarized) click.echo("") if pawpyseed: coeffs, gpoints, kpoints = _wavefunction_pawpy(bs, ibands, planewave_cutoff, ikpoints, **kwargs) else: coeffs, gpoints = _wavefunction_vasp(ibands, planewave_cutoff, ikpoints, **kwargs) kpoints = np.array([k.frac_coords for k in bs.kpoints]) structure = vr.final_structure click.echo("Writing coefficients to {}".format(output)) write_coefficients(coeffs, gpoints, kpoints, structure, filename=output)
def test_vasprun_bs(self): bsv = BSVasprun(os.path.join(test_dir, "vasprun.xml"), parse_projected_eigen=True, parse_potcar_file=True) bs = bsv.get_band_structure(kpoints_filename=os.path.join(test_dir, "KPOINTS.band"), line_mode=True) bs.get_projection_on_elements()
def read_vasprun(vasprunfile): vasprun = BSVasprun(vasprunfile) vdata = vasprun.as_dict() # pprint(vdata['input']['crystal']['lattice']['matrix']) # pprint(vdata['input']['lattice_rec']['matrix']) real_latt = vdata['input']['crystal']['lattice']['matrix'] real_latt = np.array(real_latt) reci_matrix = 2 * np.pi * np.linalg.inv(real_latt).T eigens_all = vasprun.eigenvalues if Spin(-1) not in eigens_all.keys(): eigens_up = eigens_all[Spin(1)] eigens_down = None else: eigens_up = eigens_all[Spin(1)] eigens_down = eigens_all[Spin( -1)] # eigens[ikpt][iband] = eigen, occu nelect = vdata['input']['parameters']['NELECT'] efermi = vasprun.efermi kcoords = [] for kpt in vdata['input']['kpoints']['actual_points']: kcoords.append(kpt['abc']) d = OrderedDict() d['reci_mat'] = reci_matrix d['nelect'] = int(nelect) d['efermi'] = efermi d['eigens_up'] = eigens_up d['eigens_down'] = eigens_down d['kcoords'] = np.array(kcoords) return d
def Get_bandstru(self, filepath): '''Obtain band structure''' vaspband = BSVasprun(filepath + "/vasprun.xml") self.engband = vaspband.get_band_structure(kpoints_filename=filepath + "/KPOINTS", line_mode=True) self.bandgap = self.engband.get_band_gap()['energy']
def plot_bs(vasprun_path: str): try: v = BSVasprun(vasprun_path) except xml.etree.ElementTree.ParseError: print("\tskipped due to parse error") return bs = v.get_band_structure(kpoints_filename="KPOINTS", line_mode=True) plt = BSPlotter(bs) plt.show()
def write_nn_input_coord_based(structure: IStructure, sgnum: int, index: int, all_hs_path: str, vasprun_path: str, write_dir: str, ): try: bsvasprun = BSVasprun(vasprun_path) except xml.etree.ElementTree.ParseError: print("\tskipped due to parse error") return kpoints = [tuple(vector) for vector in bsvasprun.actual_kpoints] # (kpoints, 1) bandstructure = bsvasprun.get_band_structure(kpoints_filename="KPOINTS", line_mode=True) bands = bandstructure.bands[Spin.up].T # (kpoints, bands) # connect two array kpoints_to_bands = dict(zip(kpoints, bands)) # all possible high symmetry kpoints all_hspoints = [tuple(vector) for vector in all_hspoints_from_file(all_hs_path)] # high symmetry kpoints in this structure cur_hspoints = [tuple(kpoints) for kpoints in HighSymmKpath(structure).kpath["kpoints"].values()] # filter out bands of intermediate kpoints (cur_hspoints, bands) cur_hspoints_to_bands = { kpoints: kpoints_to_bands[kpoints] for kpoints in cur_hspoints if kpoints in kpoints_to_bands } # pad zeros to missing high symmetry points (all_hspoints, bands) all_hspoints_to_bands = { hspoints: cur_hspoints_to_bands[hspoints].tolist() if (hspoints in cur_hspoints_to_bands) else [0] * bands.shape[1] for hspoints in all_hspoints } all_bands = numpy.array(list(all_hspoints_to_bands.values())).T.tolist() # (bands, all_hspoints) input_dict = {"number": sgnum, "bands": all_bands} file_path = write_dir + "theo_input_data_{}_{}.json".format(sgnum, index) with open(file_path, "w") as file: json.dump(input_dict, file, indent=4)
def Get_Strain(self, filepath): ''' Get the strain. ''' Vol = list() # number of strain = number of files - 1 for fi in filepath: vasprun = BSVasprun(fi + "vasprun.xml") Vol.append(vasprun.final_structure.volume) self.strain = [np.abs(Vol[i]-Vol[0])/Vol[0] for i in np.arange(1, len(Vol))]
def dump_wavefunction(**kwargs): """Extract wavefunction coefficients from a WAVECAR""" from amset.electronic_structure.wavefunction import ( get_wavefunction, get_wavefunction_coefficients, dump_coefficients, ) from amset.electronic_structure.common import get_ibands from amset.constants import defaults from pymatgen.io.vasp import BSVasprun output = kwargs.pop("output") planewave_cutoff = kwargs.pop("planewave_cutoff") energy_cutoff = kwargs.pop("energy_cutoff") if not energy_cutoff: energy_cutoff = defaults["energy_cutoff"] wf = get_wavefunction(**kwargs) if kwargs["directory"]: kwargs["vasprun"] = Path(kwargs["directory"]) / "vasprun.xml" vr = BSVasprun(kwargs["vasprun"]) bs = vr.get_band_structure() ibands = get_ibands(energy_cutoff, bs) click.echo("******* Getting wavefunction coefficients *******") click.echo("\nIncluding:") for spin, spin_bands in ibands.items(): min_b = spin_bands.min() + 1 max_b = spin_bands.max() + 1 click.echo(" Spin-{} bands {}—{}".format(spin.name, min_b, max_b)) click.echo("") coeffs = get_wavefunction_coefficients(wf, bs, iband=ibands, encut=planewave_cutoff) click.echo("Writing coefficients to {}".format(output)) dump_coefficients(coeffs, wf.kpts, wf.structure, filename=output)
def write_nn_input_label_based(sgnum: int, index: int, all_hs_path: str, vasprun_path: str, write_dir: str, ): try: bsvasprun = BSVasprun(vasprun_path) except xml.etree.ElementTree.ParseError: print("\tskipped due to parse error") return bandstructure = bsvasprun.get_band_structure(kpoints_filename="KPOINTS", line_mode=True) bands = bandstructure.bands[Spin.up].T # (kpoints, bands) # all possible high symmetry labels all_hslabels = all_hslabels_from_file(all_hs_path) # filter out bands of intermediate kpoints (cur_hslabels, bands) cur_hslabels_to_bands = {} for kpath in bandstructure.branches: cur_hslabels_to_bands[kpath["name"].split("-")[0]] = bands[kpath["start_index"]] cur_hslabels_to_bands[kpath["name"].split("-")[1]] = bands[kpath["end_index"]] # pad zeros to missing high symmetry labels (all_hspoints, bands) all_hslabels_to_bands = { hslabels: cur_hslabels_to_bands[hslabels].tolist() if (hslabels in cur_hslabels_to_bands) else [0] * bands.shape[1] for hslabels in all_hslabels } all_bands = numpy.array(list(all_hslabels_to_bands.values())).T.tolist() # (bands, all_hslabels) input_dict = {"number": sgnum, "bands": all_bands} file_path = write_dir + "theo_input_data_{}_{}.json".format(sgnum, index) with open(file_path, "w") as file: json.dump(input_dict, file, indent=4)
#解析晶体结构部分,输出三部分主要信息。 input_spacegroup, input_sites, input_lattice, input_structure = ParsePOSCAR( POSCAR) print(input_spacegroup, input_sites, input_lattice) print("------------------------------------------------------------") # POSCAR 晶体结构可视化 , 可视化需要软件VTK input_poscarVis = StructureVis() input_poscarVis.set_structure(input_structure) input_poscarVis.show() # 画能代结构图 , from pymatgen.io.vasp import Vasprun, BSVasprun from pymatgen.electronic_structure.plotter import BSPlotter vasprun = BSVasprun(vasprun_path) bankStructure = vasprun.get_band_structure(kpoints_filename=KPOINTS, line_mode=True) plt = BSPlotter(bankStructure) # print(plt.get_ticks()) #Get all ticks and labels for a band structure plot. return A dictionary with ‘distance’ plt.show(ylim=(-36, 5)) # 这一行有问题。就是这个范围参数该如何得到。 # 解析INCAR部分,应该直接打印 INCAR 中所有参数信息也是没问题的。 incar = ParseINCAR(INCAR) print("------------------------------------------------------------") print(incar.as_dict()) # 解析KPOINTS 部分, 需要的参数有 kpoints, nkpoints, label, kpoints = ParseKPOINTS(KPOINTS) kPoints = kpoints['kpoints']
# -*- coding: utf-8 -*- """ Created on Wed May 15 10:33:43 2019 @author: nwpuf """ from pymatgen.io.vasp import Vasprun, BSVasprun from pymatgen.electronic_structure.plotter import BSPlotter, DosPlotter import matplotlib.pyplot as plt bsv = BSVasprun("vasprun.xml") bs = bsv.get_band_structure(kpoints_filename="KPOINTS", line_mode=True) print(bs.get_band_gap()) bsplot = BSPlotter(bs) bsplot.get_plot(vbm_cbm_marker=True).show() #dosrun = Vasprun("DOS/vasprun.xml", parse_dos=True) #dos = dosrun.complete_dos #dosplot = DosPlotter(sigma=0.1) #dosplot.add_dos("Total DOS", dos) #dosplot.add_dos_dict(dos.get_element_dos()) #ax = plt.gca() #print(type(dosplot.get_plot())) #dosplot.get_plot().show()
#!/usr/bin/env python ## Application: plot band structure by pymatgen ## Written by: Asst.Prof.Dr. Kittiphong Amnuyswat ## Updated: 20/04/2020 ## Original: http://home.ustc.edu.cn/~lipai/scripts/vasp_scripts/python_plot_dos_band.html import os import sys import datetime import time sys.path.append('/Volumes/kaswat200GB/GitHub/pyVASP/') os.system('clear') print("Current date and time: ", datetime.datetime.now().strftime("%d-%m-%Y %H-%M-%S")) print("") from pymatgen.io.vasp import Vasprun, BSVasprun from pymatgen.electronic_structure.plotter import BSPlotter localDir = os.getcwd() temp = os.path.join(localDir, 'vasprun.xml') v = BSVasprun(temp) kpt = os.path.join(localDir, 'KPOINTS') bs = v.get_band_structure(kpoints_filename=kpt, line_mode=True) plt = BSPlotter(bs) plt.get_plot(vbm_cbm_marker=True) plt.save_plot('band.eps')
if Asite_element in elements: df_Asite['formula_%s' % (Asite_element)][idx + 1] = formula df_Asite['total_E_%s' % (Asite_element)][idx + 1] = tot_E df_Asite['tot_mag_%s' % (Asite_element)][idx + 1] = tot_mag df_Asite['DHf_%s' % (Asite_element)][idx + 1] = fE df_Asite['Ehull_ref_%s' % (Asite_element)][idx + 1] = entries[idx]['e_above_hull'] df_Asite['Volume_%s' % (Asite_element)][idx + 1] = volume except FileNotFoundError: # print('%03d_%s/2nd files are not found' % (idx + 1.0, formula)) f.writelines('%s files are not found\n' % (file_path)) continue try: bsv = BSVasprun(file_path + 'DOS/vasprun.xml', parse_projected_eigen = True) bs = bsv.get_band_structure(kpoints_filename = file_path + 'DOS/KPOINTS', line_mode = True) vbm = bs.as_dict()['vbm']['energy'] e_fermi = bs.as_dict()['efermi'] cbm = bs.as_dict()['cbm']['energy'] df_bulk.VBM[idx+1] = vbm df_bulk.E_fermi[idx+1] = e_fermi df_bulk.CBM[idx+1] = cbm bg = bs.get_band_gap()['energy'] bgpath = bs.get_band_gap()['transition'] if bs.get_band_gap()['direct'] == True: bgtype = 'Direct' elif bs.get_band_gap()['direct'] == False:
@Time1 : 2020-05-08 16:22:52 @Time2 : 2020/5/8 16:22 @Month1 : 5月 @Month2 : 五月 """ import plotly from pymatgen.io.vasp import BSVasprun, Vasprun from pymatgen.electronic_structure.core import Spin import plotly.graph_objs as go import chart_studio.plotly as pltly import chart_studio.tools as tls dosrun = Vasprun('AlEuO3_Perovskite_BS/vasprun.xml') run = BSVasprun("AlEuO3_Perovskite_BS/vasprun.xml", parse_projected_eigen=True) # 读取vasprun.xml bands = run.get_band_structure(kpoints_filename="AlEuO3_Perovskite_BS/KPOINTS", line_mode=True, efermi=dosrun.efermi) emin = 1e100 emax = -1e100 for spin in bands.bands.keys(): for band in range(bands.nb_bands): emin = min(emin, min(bands.bands[spin][band])) emax = max(emax, max(bands.bands[spin][band])) emin = emin - bands.efermi - 1 emax = emax - bands.efermi + 1 kptslist = [k for k in range(len(bands.kpoints))] bandTraces = list()
def Get_bandstruct(self, filepath): ''' Calculate band structure ''' vaspband = BSVasprun(filepath + "vasprun.xml") bandstru = vaspband.get_band_structure(kpoints_filename=filepath+"KPOINTS",line_mode=True) return bandstru
v = Vasprun('./vasprun.xml', parse_dos=True) cdos = v.complete_dos element_dos = cdos.get_element_dos() plotter = DosPlotter() plotter.add_dos_dict(element_dos) plotter.save_plot('plots/dos.pdf', img_format='pdf', xlim=None, ylim=None) # plotter.save_plot('spin-up_dos.pdf', img_format='pdf', xlim= None, ylim = [0,None]) # up-spin dos """ Plot Band """ from pymatgen.io.vasp import BSVasprun from pymatgen.electronic_structure.plotter import BSPlotter v = BSVasprun('./vasprun.xml', parse_projected_eigen=True) bs = v.get_band_structure(kpoints_filename='./KPOINTS', line_mode=True) bsplot = BSPlotter(bs) bsplot.get_plot(zero_to_efermi=True, ylim=[-5, 5]).savefig('plots/band.pdf') # add some features ax = plt.gca() #ax.set_title("Bandstructure", fontsize = 40) # use this for setting title xlim = ax.get_xlim() ax.hlines(0, xlim[0], xlim[1], linestyles="dashed", color="black") # add legend ax.plot((), (), "b-", label="spin up") ax.plot((), (), "r--", label="spin-down") ax.legend(fontsize=16, loc="upper left")
user_incar_settings=myset) dos.write_input(dos_dir) run_vasp(cmd, dos_dir) os.system('cp ' + dos_dir + '/vasprun.xml ./dos-vasprun.xml') # 3rd run to obtain Band structure band = MPNonSCFSet.from_prev_calc(static_dir, mode="line", standardize=True, user_incar_settings=myset) band.write_input(band_dir) run_vasp(cmd, band_dir) os.system('cp ' + band_dir + '/vasprun.xml ./band-vasprun.xml') os.system('cp ' + band_dir + '/KPOINTS ./') v = BSVasprun("band-vasprun.xml") bs = v.get_band_structure(kpoints_filename='KPOINTS', line_mode=True) plt = BSPlotter(bs) plt.get_plot(vbm_cbm_marker=True) plt.save_plot(Name + '-band.png', ylim=[-4, 4], img_format='png') v = Vasprun('dos-vasprun.xml') tdos = v.tdos cdos = v.complete_dos spd_dos = cdos.get_spd_dos() plotter = DosPlotter(sigma=0.1) plotter.add_dos("Total DOS", tdos) # plotter.add_dos("spd_dos", spd_dos) plotter.save_plot(Name + '-dos.png', img_format='png', xlim=[-4, 4]) shutil.rmtree(band_dir)
for atom in range(len(conv_struc)): magm_list.append(outcar.magnetization[atom]['tot']) df_bulk.Magm[idx + 1] = magm_list if tot_mag >= 0.5: # not a physical definition df_bulk.Mag_O[idx+1] = 'FM' elif tot_mag < 0.5: df_bulk.Mag_O[idx+1] = 'NM' except FileNotFoundError: # print('%03d_%s/2nd files are not found' % (idx + 1.0, formula)) f.writelines('%03d_%s/2nd files are not found\n' % (idx + 1.0, formula)) continue try: bsv = BSVasprun('%03d_%s/2nd/DOS/vasprun.xml' % (idx+1.0, formula), parse_projected_eigen = True) bs = bsv.get_band_structure(kpoints_filename = '%03d_%s/2nd/DOS/KPOINTS' % (idx + 1.0, formula), line_mode = True) vbm = bs.as_dict()['vbm']['energy'] e_fermi = bs.as_dict()['efermi'] cbm = bs.as_dict()['cbm']['energy'] df_bulk.VBM[idx+1] = vbm df_bulk.E_fermi[idx+1] = e_fermi df_bulk.CBM[idx+1] = cbm if bs.get_band_gap()['direct'] == True: bgtype = 'Direct' elif bs.get_band_gap()['direct'] == False: bgtype = 'Indirect'
def Get_gap_degeneracy(self, filepath): vaspband = BSVasprun(filepath + "/vasprun.xml") bandstru = vaspband.get_band_structure(kpoints_filename=filepath+"/KPOINTS",line_mode=True) self.bandgap = bandstru.get_band_gap()['energy'] self.degeneracy = bandstru.get_kpoint_degeneracy(bandstru.kpoints[self.pos['kptindex']].frac_coords)
# -*- coding: utf-8 -*- """ @Project : plotDosBS @Author : Xu-Shan Zhao @Filename: bsToMongoDB202005121111.py @IDE : PyCharm @Time1 : 2020-05-12 11:11:38 @Time2 : 2020/5/12 11:11 @Month1 : 5月 @Month2 : 五月 """ from pymatgen.io.vasp import BSVasprun import pymongo import hashlib bsvasprun = BSVasprun('AlEuO3_Perovskite_BS/vasprun.xml', parse_projected_eigen=True) bs = bsvasprun.get_band_structure(kpoints_filename='AlEuO3_Perovskite_BS/KPOINTS', line_mode=True) bs = bs.as_dict() hashvalue = hashlib.sha256(str(bs).encode('utf-8')).hexdigest() print(hashvalue) bs.update(hashvalue=hashvalue) client = pymongo.MongoClient(host='localhost', port=27017) db = client['pymatgenFormatDBs'] collection = db['band_structure'] count = collection.count_documents({"hashvalue": hashvalue}) if count == 0: collection.insert_one(bs)
#!/bin/env python3 """Alexandre Olivieri ([email protected]) Simple plot generation from the vasprun.xml and KPOINTS files.""" from pymatgen.io.vasp import BSVasprun from pymatgen.electronic_structure.plotter import BSPlotterProjected from matplotlib import pyplot as plt VRUN = BSVasprun('vasprun.xml', parse_projected_eigen=True) BS = VRUN.get_band_structure(kpoints_filename='KPOINTS', line_mode=True) BANDPLOTTER = BSPlotterProjected(BS) plot = BANDPLOTTER.get_projected_plots_dots_patom_pmorb( {'O':['p'], 'Nb':['dyz', 'dx2', 'dz2']}, {'O':['all'], 'Nb':['all']}, sum_atoms={'O':['all'], 'Nb':['all']}, sum_morbs={'O':['p']}, num_column=3 ) plot.savefig('bandstructure.pdf', dpi=1000)
completeDos = vasprun.complete_dos element_dos = completeDos.get_element_dos() plotter = DosPlotter() plotter.add_dos_dict(element_dos) plotter.add_dos('Total DOS', tdos) plotter.show() spd_dos = completeDos.get_spd_dos() plotter = DosPlotter() plotter.add_dos_dict(spd_dos) plotter.add_dos('Total DOS', tdos) plotter.show() bsvasprun_file = './AlEuO3_Perovskite_BS/vasprun.xml' kpoint_file = './AlEuO3_Perovskite_BS/KPOINTS' bsvasprun = BSVasprun(bsvasprun_file, parse_projected_eigen=True) bs = bsvasprun.get_band_structure(kpoints_filename=kpoint_file, line_mode=True) plotter = BSPlotter(bs) plotter.get_plot(vbm_cbm_marker=True) plotter.show() # banddos_fig = BSDOSPlotter() # banddos_fig = BSDOSPlotter(bs_projection=None, dos_projection=None) banddos_fig = BSDOSPlotter(bs_projection='elements', dos_projection='elements') banddos_fig.get_plot(bs=bs, dos=completeDos) import matplotlib.pyplot as plt plt.show()
def process_vasprun(self, dir_name, taskname, filename): """ Adapted from matgendb.creator Process a vasprun.xml file. """ vasprun_file = os.path.join(dir_name, filename) vrun = Vasprun(vasprun_file) d = vrun.as_dict() # rename formula keys for k, v in {"formula_pretty": "pretty_formula", "composition_reduced": "reduced_cell_formula", "composition_unit_cell": "unit_cell_formula"}.items(): d[k] = d.pop(v) for k in ["eigenvalues", "projected_eigenvalues"]: # large storage space breaks some docs if k in d["output"]: del d["output"][k] comp = Composition(d["composition_unit_cell"]) d["formula_anonymous"] = comp.anonymized_formula d["formula_reduced_abc"] = comp.reduced_composition.alphabetical_formula d["dir_name"] = os.path.abspath(dir_name) d["completed_at"] = str(datetime.datetime.fromtimestamp(os.path.getmtime(vasprun_file))) d["density"] = vrun.final_structure.density # replace 'crystal' with 'structure' d["input"]["structure"] = d["input"].pop("crystal") d["output"]["structure"] = d["output"].pop("crystal") for k, v in {"energy": "final_energy", "energy_per_atom": "final_energy_per_atom"}.items(): d["output"][k] = d["output"].pop(v) if self.parse_dos == True or (str(self.parse_dos).lower() == "auto" and vrun.incar.get("NSW", 1) == 0): try: d["dos"] = vrun.complete_dos.as_dict() except: raise ValueError("No valid dos data exist in {}.".format(dir_name)) # Band structure parsing logic if str(self.bandstructure_mode).lower() == "auto": # if line mode nscf if vrun.incar.get("ICHARG", 0) > 10 and vrun.kpoints.num_kpts > 0: bs_vrun = BSVasprun(vasprun_file, parse_projected_eigen=True) bs = bs_vrun.get_band_structure(line_mode=True) # else if nscf elif vrun.incar.get("ICHARG", 0) > 10: bs_vrun = BSVasprun(vasprun_file, parse_projected_eigen=True) bs = bs_vrun.get_band_structure() # else just regular calculation else: bs = vrun.get_band_structure() # only save the bandstructure if not moving ions if vrun.incar["NSW"] == 0: d["bandstructure"] = bs.as_dict() # legacy line/True behavior for bandstructure_mode elif self.bandstructure_mode: bs_vrun = BSVasprun(vasprun_file, parse_projected_eigen=True) bs = bs_vrun.get_band_structure(line_mode=(str(self.bandstructure_mode).lower() == "line")) d["bandstructure"] = bs.as_dict() # parse bandstructure for vbm/cbm/bandgap but don't save else: bs = vrun.get_band_structure() # Parse electronic information if possible. # For certain optimizers this is broken and we don't get an efermi resulting in the bandstructure try: bs_gap = bs.get_band_gap() d["output"]["vbm"] = bs.get_vbm()["energy"] d["output"]["cbm"] = bs.get_cbm()["energy"] d["output"]["bandgap"] = bs_gap["energy"] d["output"]["is_gap_direct"] = bs_gap["direct"] d["output"]["is_metal"] = bs.is_metal() if not bs_gap["direct"]: d["output"]["direct_gap"] = bs.get_direct_band_gap() if isinstance(bs, BandStructureSymmLine): d["output"]["transition"] = bs_gap["transition"] except Exception: if self.bandstructure_mode is True: import traceback logger.error(traceback.format_exc()) logger.error("Error in " + os.path.abspath(dir_name) + ".\n" + traceback.format_exc()) raise logger.warning("Error in parsing bandstructure") if vrun.incar["IBRION"] == 1: logger.warning("Vasp doesn't properly output efermi for IBRION == 1") d["task"] = {"type": taskname, "name": taskname} d["output_file_paths"] = self.process_raw_data(dir_name, taskname=taskname) if "locpot" in d["output_file_paths"] and self.parse_locpot: locpot = Locpot.from_file(os.path.join(dir_name, d["output_file_paths"]["locpot"])) d["output"]["locpot"] = {i: locpot.get_average_along_axis(i) for i in range(3)} if hasattr(vrun, "force_constants"): # phonon-dfpt d["output"]["force_constants"] = vrun.force_constants.tolist() d["output"]["normalmode_eigenvals"] = vrun.normalmode_eigenvals.tolist() d["output"]["normalmode_eigenvecs"] = vrun.normalmode_eigenvecs.tolist() return d
print(hashvalue) complete_dos.update(hashvalue=hashvalue) client = pymongo.MongoClient(host='localhost', port=27017) db = client['pymatgenFormatDBs'] collection = db['complete_dos'] count = collection.count_documents({"hashvalue":hashvalue}) if count == 0: collection.insert_one(complete_dos) else: print("Same data is exist in DB.") # Then band_structures bsvasprun = BSVasprun('AlEuO3_Perovskite_BS/vasprun.xml') bs = bsvasprun.get_band_structure().as_dict() client = pymongo.MongoClient(host='localhost', port=27017) db = client['pymatgenFormatDBs'] collection = db['band_structures'] hashvalue = hashlib.sha256(str(bs).encode('utf-8')).hexdigest() print(hashvalue) bs.update(hashvalue=hashvalue) count = collection.count_documents({"hashvalue":hashvalue}) if count == 0: collection.insert_one(bs)