def plot_bandstructure(): if "-h" in sys.argv: print("usage: complot_bands.py [-g] [-f fname] [-el emin] [-eh emax]") sys.exit() if "-g" in sys.argv: mode = "risb" else: mode = "tb" bs = get_bands_symkpath(mode=mode) comm = MPI.COMM_WORLD rank = comm.Get_rank() if rank == 0: bsplot = BSPlotter(bs) if "-f" in sys.argv: fname = sys.argv[sys.argv.index("-f")+1] if ".pdf" not in fname: fname += ".pdf" else: fname = "bndstr.pdf" if "-el" in sys.argv: emin = float(sys.argv[sys.argv.index("-el")+1]) else: emin = numpy.min(bs.bands.values()) if "-eh" in sys.argv: emax = float(sys.argv[sys.argv.index("-eh")+1]) else: emax = numpy.max(bs.bands.values()) bsplot.save_plot(fname, img_format="pdf", ylim=(emin, emax), \ zero_to_efermi=False)
def get_mp_banddos(): check_matplotlib() mpr = check_apikey() print("input the mp-ID") wait_sep() in_str = wait() mp_id = in_str step_count = 1 proc_str = "Reading Data From " + web + " ..." procs(proc_str, step_count, sp='-->>') data = mpr.get_entry_by_material_id(mp_id) sepline() print(data) sepline() step_count += 1 proc_str = "Reading Band Data From " + web + " ..." procs(proc_str, step_count, sp='-->>') band = mpr.get_bandstructure_by_material_id(mp_id) if band is None: print("No data obtained online, stop now!") os.exit(0) step_count += 1 filename = mp_id + '_band.png' proc_str = "Writing Data to " + filename + " File..." bsp = BSPlotter(band) procs(proc_str, step_count, sp='-->>') bsp.save_plot(filename=filename, img_format="png") step_count += 1 proc_str = "Reading DOS Data From " + web + " ..." procs(proc_str, step_count, sp='-->>') dos = mpr.get_dos_by_material_id(mp_id) if dos is None: print("No data obtained online, stop now!") step_count += 1 filename = mp_id + '_dos.png' proc_str = "Writing Data to " + filename + " File..." dsp = DosPlotter() dsp.add_dos('Total', dos) procs(proc_str, step_count, sp='-->>') dsp.save_plot(filename=filename, img_format="png")
class BSPlotterTest(unittest.TestCase): def setUp(self): with open(os.path.join(test_dir, "CaO_2605_bandstructure.json"), "r", encoding='utf-8') as f: d = json.loads(f.read()) self.bs = BandStructureSymmLine.from_dict(d) self.plotter = BSPlotter(self.bs) warnings.simplefilter("ignore") def tearDown(self): warnings.simplefilter("default") def test_bs_plot_data(self): self.assertEqual(len(self.plotter.bs_plot_data()['distances'][0]), 16, "wrong number of distances in the first branch") self.assertEqual(len(self.plotter.bs_plot_data()['distances']), 10, "wrong number of branches") self.assertEqual( sum([len(e) for e in self.plotter.bs_plot_data()['distances']]), 160, "wrong number of distances") self.assertEqual(self.plotter.bs_plot_data()['ticks']['label'][5], "K", "wrong tick label") self.assertEqual(len(self.plotter.bs_plot_data()['ticks']['label']), 19, "wrong number of tick labels") # Minimal baseline testing for get_plot. not a true test. Just checks that # it can actually execute. def test_get_plot(self): # zero_to_efermi = True, ylim = None, smooth = False, # vbm_cbm_marker = False, smooth_tol = None # Disabling latex is needed for this test to work. from matplotlib import rc rc('text', usetex=False) plt = self.plotter.get_plot() plt = self.plotter.get_plot(smooth=True) plt = self.plotter.get_plot(vbm_cbm_marker=True) self.plotter.save_plot("bsplot.png") self.assertTrue(os.path.isfile("bsplot.png")) os.remove("bsplot.png") plt.close("all")
class BSPlotterTest(unittest.TestCase): def setUp(self): with open(os.path.join(test_dir, "CaO_2605_bandstructure.json"), "r", encoding='utf-8') as f: d = json.loads(f.read()) self.bs = BandStructureSymmLine.from_dict(d) self.plotter = BSPlotter(self.bs) warnings.simplefilter("ignore") def tearDown(self): warnings.resetwarnings() def test_bs_plot_data(self): self.assertEqual(len(self.plotter.bs_plot_data()['distances'][0]), 16, "wrong number of distances in the first branch") self.assertEqual(len(self.plotter.bs_plot_data()['distances']), 10, "wrong number of branches") self.assertEqual( sum([len(e) for e in self.plotter.bs_plot_data()['distances']]), 160, "wrong number of distances") self.assertEqual(self.plotter.bs_plot_data()['ticks']['label'][5], "K", "wrong tick label") self.assertEqual(len(self.plotter.bs_plot_data()['ticks']['label']), 19, "wrong number of tick labels") # Minimal baseline testing for get_plot. not a true test. Just checks that # it can actually execute. def test_get_plot(self): # zero_to_efermi = True, ylim = None, smooth = False, # vbm_cbm_marker = False, smooth_tol = None # Disabling latex is needed for this test to work. from matplotlib import rc rc('text', usetex=False) plt = self.plotter.get_plot() plt = self.plotter.get_plot(smooth=True) plt = self.plotter.get_plot(vbm_cbm_marker=True) self.plotter.save_plot("bsplot.png") self.assertTrue(os.path.isfile("bsplot.png")) os.remove("bsplot.png")
# !/usr/bin/env python # -*- coding: utf-8 -*- from pymatgen.io.vasp.outputs import Vasprun from pymatgen.electronic_structure.plotter import BSPlotter vasprun = Vasprun("vasprun.xml") bss = vasprun.get_band_structure(kpoints_filename="KPOINTS", line_mode=True) plotter = BSPlotter(bss) #plotter.save_plot("bandStructure.svg", img_format="svg") #plotter.save_plot("bandStructure.png", img_format="png") #plotter.save_plot("lim_bandStructure.svg", img_format="svg", ylim=(-.2, 1.4)) plotter.save_plot("MAPbI3-primitive.png", img_format="png", ylim=(-5, 5)) plotter.plot_brillouin()
# Distributed under the terms of the MIT License. from __future__ import division, print_function, unicode_literals, \ absolute_import """ reads in KPOINTS(with labels for high symmetry kpoints) and vasprun.xml files and plots the band structure along the high symmetry kpoints """ # To use matplotlib on Hipergator, uncomment the following 2 lines: # import matplotlib # matplotlib.use('Agg') from pymatgen.io.vasp.outputs import Vasprun from pymatgen.electronic_structure.plotter import BSPlotter if __name__ == "__main__": # readin bandstructure from vasprun.xml and labeled KPOINTS run = Vasprun("vasprun.xml", parse_projected_eigen=True) bands = run.get_band_structure("KPOINTS", line_mode=True, efermi=run.efermi) bsp = BSPlotter(bands) # Blue lines are up spin, red lines are down spin bsp.save_plot('band_diagram.eps', ylim=(-5, 5)) # bsp = BSPlotterProjected(bands) # plt = bsp.get_projected_plots_dots( {'Fe':['s', 'p', 'd'], # 'Sb':['s', 'p', 'd']}) # get_elt_projected_plots_color()
def band_structure(): check_matplotlib() step_count=1 filename='vasprun.xml' check_file(filename) proc_str="Reading Data From "+ filename +" File ..." procs(proc_str,step_count,sp='-->>') vsr=Vasprun(filename) step_count+=1 filename='KPOINTS' check_file(filename) proc_str="Reading Data From "+ filename +" File ..." procs(proc_str,step_count,sp='-->>') bands = vsr.get_band_structure(filename, line_mode=True, efermi=vsr.efermi) step_count+=1 filename='OUTCAR' check_file(filename) proc_str="Reading Data From "+ filename +" File ..." procs(proc_str,step_count,sp='-->>') outcar=Outcar('OUTCAR') mag=outcar.as_dict()['total_magnetization'] if vsr.is_spin: proc_str="This Is a Spin-polarized Calculation." procs(proc_str,0,sp='-->>') tdos=vsr.tdos SpinUp_gap=tdos.get_gap(spin=Spin.up) cbm_vbm_up=tdos.get_cbm_vbm(spin=Spin.up) SpinDown_gap=tdos.get_gap(spin=Spin.down) cbm_vbm_down=tdos.get_cbm_vbm(spin=Spin.up) if SpinUp_gap > min_gap and SpinDown_gap > min_gap: is_metal=False is_semimetal=False elif SpinUp_gap > min_gap and SpinDown_gap < min_gap: is_metal=False is_semimetal=True elif SpinUp_gap < min_gap and SpinDown_gap > min_gap: is_metal=False is_semimetal=True elif SpinUp_gap < min_gap and SpinDown_gap < min_gap: is_metal=True is_semimetal=False if is_metal: proc_str="This Material Is a Metal." procs(proc_str,0,sp='-->>') if not is_metal and is_semimetal: proc_str="This Material Is a Semimetal." procs(proc_str,0,sp='-->>') else: proc_str="This Material Is a Semiconductor." procs(proc_str,0,sp='-->>') proc_str="Total magnetization is "+str(mag) procs(proc_str,0,sp='-->>') if mag > min_mag: proc_str="SpinUp : vbm=%f eV cbm=%f eV gap=%f eV"%(cbm_vbm_up[1],cbm_vbm_up[0],SpinUp_gap) procs(proc_str,0,sp='-->>') proc_str="SpinDown: vbm=%f eV cbm=%f eV gap=%f eV"%(cbm_vbm_down[1],cbm_vbm_down[0],SpinUp_gap) procs(proc_str,0,sp='-->>') else: proc_str="SpinUp : vbm=%f eV cbm=%f eV gap=%f eV"%(cbm_vbm_up[1],cbm_vbm_up[0],SpinUp_gap) procs(proc_str,0,sp='-->>') step_count+=1 filename="BAND.dat" proc_str="Writting Band Structure Data to "+ filename +" File ..." procs(proc_str,step_count,sp='-->>') band_data_up=bands.bands[Spin.up] band_data_down=bands.bands[Spin.down] y_data_up=band_data_up.reshape(1,band_data_up.shape[0]*band_data_up.shape[1])[0]-vsr.efermi #shift fermi level to 0 y_data_down=band_data_down.reshape(1,band_data_down.shape[0]*band_data_down.shape[1])[0]-vsr.efermi #shift fermi level to 0 x_data=np.array(bands.distance*band_data_up.shape[0]) data=np.vstack((x_data,y_data_up,y_data_down)).T head_line="#%(key1)+12s%(key2)+13s%(key3)+15s"%{'key1':'K-Distance','key2':'UpEnergy(ev)','key3':'DownEnergy(ev)'} write_col_data(filename,data,head_line,band_data_up.shape[1]) else: if vsr.parameters['LNONCOLLINEAR']: proc_str="This Is a Non-Collinear Calculation." else: proc_str="This Is a Non-Spin Calculation." procs(proc_str,0,sp='-->>') cbm=bands.get_cbm()['energy'] vbm=bands.get_vbm()['energy'] gap=bands.get_band_gap()['energy'] if not bands.is_metal(): proc_str="This Material Is a Semiconductor." procs(proc_str,0,sp='-->>') proc_str="vbm=%f eV cbm=%f eV gap=%f eV"%(vbm,cbm,gap) procs(proc_str,0,sp='-->>') else: proc_str="This Material Is a Metal." procs(proc_str,0,sp='-->>') step_count+=1 filename3="BAND.dat" proc_str="Writting Band Structure Data to "+ filename3 +" File ..." procs(proc_str,step_count,sp='-->>') band_data=bands.bands[Spin.up] y_data=band_data.reshape(1,band_data.shape[0]*band_data.shape[1])[0]-vsr.efermi #shift fermi level to 0 x_data=np.array(bands.distance*band_data.shape[0]) data=np.vstack((x_data,y_data)).T head_line="#%(key1)+12s%(key2)+13s"%{'key1':'K-Distance','key2':'Energy(ev)'} write_col_data(filename3,data,head_line,band_data.shape[1]) step_count+=1 bsp=BSPlotter(bands) filename4="HighSymmetricPoints.dat" proc_str="Writting Label infomation to "+ filename4 +" File ..." procs(proc_str,step_count,sp='-->>') head_line="#%(key1)+12s%(key2)+12s%(key3)+12s"%{'key1':'index','key2':'label','key3':'position'} line=head_line+'\n' for i,label in enumerate(bsp.get_ticks()['label']): new_line="%(key1)12d%(key2)+12s%(key3)12f\n"%{'key1':i,'key2':label,'key3':bsp.get_ticks()['distance'][i]} line+=new_line line+='\n' write_col_data(filename4,line,'',str_data=True) try: step_count+=1 filename5="BAND.png" proc_str="Saving Plot to "+ filename5 +" File ..." procs(proc_str,step_count,sp='-->>') bsp.save_plot(filename5, img_format="png") except: print("Figure output fails !!!")
class BSPlotterTest(unittest.TestCase): def setUp(self): with open(os.path.join(test_dir, "CaO_2605_bandstructure.json"), "r", encoding="utf-8") as f: d = json.loads(f.read()) self.bs = BandStructureSymmLine.from_dict(d) self.plotter = BSPlotter(self.bs) self.assertEqual(len(self.plotter._bs), 1, "wrong number of band objects") with open(os.path.join(test_dir, "N2_12103_bandstructure.json"), "r", encoding="utf-8") as f: d = json.loads(f.read()) self.sbs_sc = BandStructureSymmLine.from_dict(d) with open(os.path.join(test_dir, "C_48_bandstructure.json"), "r", encoding="utf-8") as f: d = json.loads(f.read()) self.sbs_met = BandStructureSymmLine.from_dict(d) self.plotter_multi = BSPlotter([self.sbs_sc, self.sbs_met]) self.assertEqual(len(self.plotter_multi._bs), 2, "wrong number of band objects") self.assertEqual(self.plotter_multi._nb_bands, [96, 96], "wrong number of bands") warnings.simplefilter("ignore") def tearDown(self): warnings.simplefilter("default") def test_add_bs(self): self.plotter_multi.add_bs(self.sbs_sc) self.assertEqual(len(self.plotter_multi._bs), 3, "wrong number of band objects") self.assertEqual(self.plotter_multi._nb_bands, [96, 96, 96], "wrong number of bands") def test_get_branch_steps(self): steps_idx = BSPlotter._get_branch_steps(self.sbs_sc.branches) self.assertEqual(steps_idx, [0, 121, 132, 143], "wrong list of steps idx") def test_rescale_distances(self): rescaled_distances = self.plotter_multi._rescale_distances( self.sbs_sc, self.sbs_met) self.assertEqual( len(rescaled_distances), len(self.sbs_met.distance), "wrong lenght of distances list", ) self.assertEqual(rescaled_distances[-1], 6.5191398067252875, "wrong last distance value") self.assertEqual( rescaled_distances[148], self.sbs_sc.distance[19], "wrong distance at high symm k-point", ) def test_interpolate_bands(self): data = self.plotter.bs_plot_data() d = data["distances"] en = data["energy"]["1"] int_distances, int_energies = self.plotter._interpolate_bands(d, en) self.assertEqual(len(int_distances), 10, "wrong lenght of distances list") self.assertEqual(len(int_distances[0]), 100, "wrong lenght of distances in a branch") self.assertEqual(len(int_energies), 10, "wrong lenght of distances list") self.assertEqual(int_energies[0].shape, (16, 100), "wrong lenght of distances list") def test_bs_plot_data(self): self.assertEqual( len(self.plotter.bs_plot_data()["distances"]), 10, "wrong number of sequences of branches", ) self.assertEqual( len(self.plotter.bs_plot_data()["distances"][0]), 16, "wrong number of distances in the first sequence of branches", ) self.assertEqual( sum([len(e) for e in self.plotter.bs_plot_data()["distances"]]), 160, "wrong number of distances", ) lenght = len( self.plotter.bs_plot_data(split_branches=False)["distances"][0]) self.assertEqual( lenght, 144, "wrong number of distances in the first sequence of branches") lenght = len( self.plotter.bs_plot_data(split_branches=False)["distances"]) self.assertEqual( lenght, 2, "wrong number of distances in the first sequence of branches") self.assertEqual(self.plotter.bs_plot_data()["ticks"]["label"][5], "K", "wrong tick label") self.assertEqual( len(self.plotter.bs_plot_data()["ticks"]["label"]), 19, "wrong number of tick labels", ) def test_get_ticks(self): self.assertEqual(self.plotter.get_ticks()["label"][5], "K", "wrong tick label") self.assertEqual( self.plotter.get_ticks()["distance"][5], 2.406607625322699, "wrong tick distance", ) # Minimal baseline testing for get_plot. not a true test. Just checks that # it can actually execute. def test_get_plot(self): # zero_to_efermi = True, ylim = None, smooth = False, # vbm_cbm_marker = False, smooth_tol = None # Disabling latex is needed for this test to work. from matplotlib import rc rc("text", usetex=False) plt = self.plotter.get_plot() self.assertEqual(plt.ylim(), (-4.0, 7.6348), "wrong ylim") plt = self.plotter.get_plot(smooth=True) plt = self.plotter.get_plot(vbm_cbm_marker=True) self.plotter.save_plot("bsplot.png") self.assertTrue(os.path.isfile("bsplot.png")) os.remove("bsplot.png") plt.close("all") # test plotter with 2 bandstructures plt = self.plotter_multi.get_plot() self.assertEqual(len(plt.gca().get_lines()), 874, "wrong number of lines") self.assertEqual(plt.ylim(), (-10.0, 10.0), "wrong ylim") plt = self.plotter_multi.get_plot(zero_to_efermi=False) self.assertEqual(plt.ylim(), (-15.2379, 12.67141266), "wrong ylim") plt = self.plotter_multi.get_plot(smooth=True) self.plotter_multi.save_plot("bsplot.png") self.assertTrue(os.path.isfile("bsplot.png")) os.remove("bsplot.png") plt.close("all")
# 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) shutil.rmtree(dos_dir) shutil.rmtree(static_dir) os.chdir('../')
from pymatgen.io.vasp import Vasprun from pymatgen.electronic_structure.plotter import BSPlotter, BSPlotterProjected vr = Vasprun("nself/vasprun.xml") bs = vr.get_band_structure(kpoints_filename="nself/KPOINTS", line_mode=True) bsp = BSPlotter(bs) #plt = bsp.get_elt_projected_plots(zero_to_efermi=False) #plt.savefig("band_structure.png", format="png") bsp.save_plot(filename="band_structure.png", img_format="png")
# Copyright (c) Henniggroup. # Distributed under the terms of the MIT License. from __future__ import division, unicode_literals, print_function """ reads in KPOINTS(with labels for high symmetry kpoints) and vasprun.xml files and plots the band structure along the high symmetry kpoints """ # To use matplotlib on Hipergator, uncomment the following 2 lines: # import matplotlib # matplotlib.use('Agg') from pymatgen.io.vasp.outputs import Vasprun from pymatgen.electronic_structure.plotter import BSPlotterProjected, BSPlotter if __name__ == "__main__": # readin bandstructure from vasprun.xml and labeled KPOINTS run = Vasprun("vasprun.xml", parse_projected_eigen=True) bands = run.get_band_structure("KPOINTS", line_mode=True, efermi=run.efermi) bsp = BSPlotter(bands) # Blue lines are up spin, red lines are down spin bsp.save_plot('band_diagram.eps', ylim=(-5, 5)) # bsp = BSPlotterProjected(bands) # plt = bsp.get_projected_plots_dots( {'Fe':['s', 'p', 'd'], # 'Sb':['s', 'p', 'd']}) # get_elt_projected_plots_color()
#!/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')
from __future__ import division, unicode_literals, print_function """ reads in KPOINTS(with labels for high symmetry kpoints) and vasprun.xml files and plots the band structure along the high symmetry kpoints """ # To use matplotlib on Hipergator, uncomment the following 2 lines: # import matplotlib # matplotlib.use('Agg') from pymatgen.io.vasp.outputs import Vasprun from pymatgen.electronic_structure.plotter import BSPlotterProjected, BSPlotter if __name__ == "__main__": # readin bandstructure from vasprun.xml and labeled KPOINTS run = Vasprun("vasprun.xml", parse_projected_eigen=True) bands = run.get_band_structure("KPOINTS", line_mode=True, efermi=run.efermi) bsp = BSPlotter(bands) # Blue lines are up spin, red lines are down spin bsp.save_plot("band_diagram.eps", ylim=(-5, 5)) # bsp = BSPlotterProjected(bands) # plt = bsp.get_projected_plots_dots( {'Fe':['s', 'p', 'd'], # 'Sb':['s', 'p', 'd']}) # get_elt_projected_plots_color()