def plot_band_structure(ylim=(-5, 5), draw_fermi=False, fmt='pdf'): """ Plot a standard band structure with no projections. Args: ylim (tuple): minimum and maximum potentials for the plot's y-axis. draw_fermi (bool): whether or not to draw a dashed line at E_F. fmt (str): matplotlib format style. Check the matplotlib docs for options. """ vasprun = Vasprun('vasprun.xml') efermi = vasprun.efermi bsp = BSPlotter( vasprun.get_band_structure('KPOINTS', line_mode=True, efermi=efermi)) if fmt == "None": return bsp.bs_plot_data() else: plot = bsp.get_plot(ylim=ylim) fig = plot.gcf() ax = fig.gca() ax.set_xticklabels( [r'$\mathrm{%s}$' % t for t in ax.get_xticklabels()]) ax.set_yticklabels( [r'$\mathrm{%s}$' % t for t in ax.get_yticklabels()]) if draw_fermi: ax.plot([ax.get_xlim()[0], ax.get_xlim()[1]], [0, 0], 'k--') plt.savefig('band_structure.{}'.format(fmt), transparent=True) plt.close()
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")
def plot_bs(bs, **kwargs): """ Get BS plot with pymatgen. Parameters ---------- bs : BandStructureSymmLine object, most likely generaten from Vasprun or BSVasprun. **kwargs : (dict) Arguments for the get_plot function in BSPlotter in pymatgen. Returns ------- plt : Matplotlib object. """ plotter = BSPlotter(bs) plt = plotter.get_plot(**kwargs) return plt
def plot_band_structure(ylim=(-5, 5), draw_fermi=False, fmt="pdf"): """ Plot a standard band structure with no projections. Args: ylim (tuple): minimum and maximum potentials for the plot's y-axis. draw_fermi (bool): whether or not to draw a dashed line at E_F. fmt (str): matplotlib format style. Check the matplotlib docs for options. """ vasprun = Vasprun("vasprun.xml") efermi = vasprun.efermi bsp = BSPlotter(vasprun.get_band_structure("KPOINTS", line_mode=True, efermi=efermi)) plot = bsp.get_plot(ylim=ylim) fig = plot.gcf() ax = fig.gca() ax.set_xticklabels([r"$\mathrm{%s}$" % t for t in ax.get_xticklabels()]) if draw_fermi: ax.plot([ax.get_xlim()[0], ax.get_xlim()[1]], [0, 0], "k--") fig.savefig("band_structure.{}".format(fmt), transparent=True) plt.close()
from pymatgen.electronic_structure.plotter import BSPlotter, BSPlotterProjected from pymatgen.io.vasp import Vasprun, BandStructure v = Vasprun("AgTe_bs/vasprun.xml") bands = v.get_band_structure(kpoints_filename="AgTe_bs/KPOINTS", line_mode=True) print(bands.get_band_gap()) plt = BSPlotter(bands) #plt.plot_brillouin() plt.get_plot(zero_to_efermi=True, vbm_cbm_marker=True, ylim=(-3, 3)).show() #plt.get_plot(zero_to_efermi=True,vbm_cbm_marker=True,ylim=(-2.2,0.5)).savefig(fname="bs.eps",img_format="eps")
# !/usr/bin/env python # -*- coding:utf-8 -*- # author:春梅 from pymatgen.ext.matproj import MPRester from pymatgen.electronic_structure.core import Spin #This initiliazes the Rest connection to the Materials Project db. Put your own API key if needed. #这个初始化的其余连接到材料项目DB。如果需要的话,你可以把你自己的api键放上去。 a = MPRester("hvSDrzMafUtXE0JQ") #load the band structure from mp-3748, CuAlO2 from the MP db #从mp-3748加载频段带结构,从mp dB加载cualo2 bs = a.get_bandstructure_by_material_id("mp-3748") #is the material a metal (i.e., the fermi level cross a band) #输出是金属的材料(即费米级交叉带) print(bs.is_metal()) #print information on the band gap #禁带宽度(Band gap)是指一个带隙宽度(单位是电子伏特(ev)),固体中电子的能量是不可以连续取值的,而是一些不连续的能带,要导电就要有自由电子或者空穴存在,自由电子存在的能带称为导带(能导电),自由空穴存在的能带称为价带(亦能导电) print(bs.get_band_gap()) #print the energy of the 20th band and 10th kpoint #打印20波段和10坐标的计算能带的能量(我只查到这个计算能带是vasp中的内容,kpoint是对应的坐标,具体对于VASP我也不是很了解) print(bs.bands[Spin.up][20][10]) #print energy of direct band gap print(bs.get_direct_band_gap()) #print information on the vbm print(bs.get_vbm()) #%matplotlib inline from pymatgen.electronic_structure.plotter import BSPlotter plotter = BSPlotter(bs) plotter.get_plot().show() plotter.plot_brillouin()
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")
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") bs.as_dict()['vbm'] bs.as_dict()['cbm']
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) shutil.rmtree(dos_dir) shutil.rmtree(static_dir)
def bs_graph(rawdatadir, savedir, e_fermi, soc=False): run = BSVasprun("{}/vasprun.xml".format(rawdatadir), parse_projected_eigen=True) bs = run.get_band_structure(efermi=e_fermi, line_mode=True, force_hybrid_mode=True) bsplot = BSPlotter(bs) # Get the plot bsplot.get_plot(vbm_cbm_marker=True, ylim=(-1.5, 1.5), zero_to_efermi=True) bs_graph.e_fermi = float(bs.efermi) bs_graph.band_gap = float(bs.get_band_gap()["energy"]) ax = plt.gca() xlim = ax.get_xlim() ylim = ax.get_ylim() ax.hlines(0, xlim[0], xlim[1], linestyle="--", color="black") ax.tick_params(labelsize=20) if not soc: ax.plot((), (), "r-", label="spin up") ax.plot((), (), "b-", label="spin down") ax.legend(fontsize=16, loc="upper left") plt.savefig("{}/BSGraph".format(savedir)) plt.close() if not soc: # Print quick info about band gap (source: vasprun.xml) #print(bs_graph.e_fermi) #print(bs_graph.band_gap) # Get quick info about band gap (source: EIGENVAL) eigenval = Eigenval("{}/EIGENVAL".format(rawdatadir)) bs_graph.band_properties = eigenval.eigenvalue_band_properties # Get detailed info about band gap and CB/VB in each spin channel # (source: EIGENVAL) bs_graph.eigenvalues = eigenval.eigenvalues bs_graph.kpoints = eigenval.kpoints poscar = Poscar.from_file("{}/POSCAR".format(rawdatadir)) bs_graph.lattice = poscar.structure.lattice.reciprocal_lattice bs_graph.eigenvalues[Spin.up] = bs_graph.eigenvalues[ Spin.up][:, :, :-1] bs_graph.eigenvalues[Spin.down] = bs_graph.eigenvalues[ Spin.down][:, :, :-1] bs_graph.eigenvalues[Spin.up] = bs_graph.eigenvalues[Spin.up][:, :, 0] bs_graph.eigenvalues[Spin.down] = bs_graph.eigenvalues[Spin.down][:, :, 0] bs_graph.eigenvalues[Spin.up] = \ np.transpose(bs_graph.eigenvalues[Spin.up]) bs_graph.eigenvalues[Spin.down] = \ np.transpose(bs_graph.eigenvalues[Spin.down]) bs = BandStructure(bs_graph.kpoints, bs_graph.eigenvalues, bs_graph.lattice, bs_graph.e_fermi) bs_graph.vbm = bs.get_vbm()["energy"] bs_graph.cbm = bs.get_cbm()["energy"] bs_graph.electronic_gap = bs.get_band_gap()["energy"] bs_graph.direct = bs.get_band_gap()["direct"] if bs_graph.vbm and bs_graph.cbm and bs_graph.electronic_gap: bs_graph.gap_by_spin = bs.get_direct_band_gap_dict() return
from pymatgen.io.vasp.outputs import BSVasprun from pymatgen.electronic_structure.plotter import BSPlotter import pylab pylab.rcParams.update({'font.size': 48, 'text.usetex': True}) bs = BSVasprun('vasprun.xml') bst = bs.get_band_structure() plotter = BSPlotter(bst) plt = plotter.get_plot() plt.ylabel("$E - E_f$ (eV)") plt.xlabel("") plt.tight_layout() plt.show()
#!/usr/bin python # -*- encoding: utf-8 -*- ''' @Author : Celeste Young @File : 能带图.py @Time : 2020/12/30 13:42 @Tips : ''' import matplotlib.pyplot as plt from pymatgen.io.vasp.outputs import Vasprun from pymatgen.electronic_structure.plotter import BSDOSPlotter, BSPlotter, BSPlotterProjected, DosPlotter bs_vasprun = Vasprun("vasprun.xml", parse_projected_eigen=True) bs_data = bs_vasprun.get_band_structure(line_mode=True) dos_data = bs_vasprun.complete_dos banddos_fig = BSDOSPlotter(bs_projection=None, \ dos_projection=None, vb_energy_range=-5, \ fixed_cb_energy=5) band_fig = BSPlotter(bs=bs_data) band_fig.get_plot() plt.ylim(-2, 1)
# -*- 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()
from pymatgen.electronic_structure.plotter import BSPlotter, BSDOSPlotter, DosPlotter import matplotlib.pyplot as plt run = BSVasprun('./vasprun.xml', parse_projected_eigen=True) bs = run.get_band_structure("KPOINTS") n = 0 for kpoints, e in zip(bs.kpoints, bs.bands[Spin.up][9,:]): n += 1 if n == 11: print('...') if 10 < n < 90: continue print("kx = %5.3f ky = %5.3f kz = %5.3f eps(k) = %8.4f" %(tuple(kpoints.frac_coords) + (e,))) bsplot = BSPlotter(bs) bsplot.get_plot(ylim=(-20, 10), zero_to_efermi=True) print(bs.efermi) ax = plt.gca() ax.set_title("NiO Band Structure", fontsize=20) xlim = ax.get_xlim() ax.hlines(0, xlim[0], xlim[1], linestyles='dashed', color='black') ax.plot((), (), 'b-', label="spin up") ax.plot((), (), 'r--', label="spin down") ax.legend(fontsize=16, loc='upper left') # plt.show()
dosplotter = DosPlotter() Totaldos = dosplotter.add_dos('Total DOS', tdos) Integrateddos = dosplotter.add_dos('Integrated DOS', idos) #Pdos = dosplotter.add_dos('Partial DOS',pdos) #Spd_dos = dosplotter.add_dos('spd DOS',spd_dos) #Element_dos = dosplotter.add_dos('Element DOS',element_dos) #Element_spd_dos = dosplotter.add_dos('Element_spd DOS',element_spd_dos) dos_dict = { 'Total DOS': tdos, 'Integrated DOS': idos } #'Partial DOS':pdos,'spd DOS':spd_dos,'Element DOS':element_dos}#'Element_spd DOS':element_spd_dos add_dos_dict = dosplotter.add_dos_dict(dos_dict) get_dos_dict = dosplotter.get_dos_dict() dos_plot = dosplotter.get_plot() ##dosplotter.save_plot("MAPbI3_dos",img_format="png") ##dos_plot.show() bsplotter = BSPlotter(bs) bs_plot_data = bsplotter.bs_plot_data() bs_plot = bsplotter.get_plot() #bsplotter.save_plot("MAPbI3_bs",img_format="png") #bsplotter.show() ticks = bsplotter.get_ticks() print ticks bsplotter.plot_brillouin() bsdos = BSDOSPlotter( tick_fontsize=10, egrid_interval=20, dos_projection="orbitals", bs_legend=None) #bs_projection="HPbCIN",dos_projection="HPbCIN") bds = bsdos.get_plot(bs, cdos)
# print(dos.efermi) dosplot1 = DosPlotter(sigma=0.05) dosplot1.add_dos("Total DOS", dos) plt = dosplot1.get_plot(xlim=(-18, 15)) plt.grid() plt.savefig("pymatgen_DOS.eps", format="eps") plt.show() plt.close() # bsrun = BSVasprun("Band/vasprun.xml", parse_projected_eigen=True) bsrun = BSVasprun("Band/vasprun.xml") bs = bsrun.get_band_structure("Band/KPOINTS") bsplot = BSPlotter(bs) plt = bsplot.get_plot(bs) bsplot.plot_brillouin() bsplot.get_plot(ylim=(-18, 15), zero_to_efermi=True) plt.grid() plt.savefig("pymatgen_Band.eps", format="eps") plt.show() plt.close() # run = BSVasprun("Band/vasprun.xml", parse_projected_eigen=True) # dosrun = Vasprun("DOS/vasprun.xml", parse_dos=True) # dosrun = Vasprun("vasprun.xml", parse_dos=True) # dos = dosrun.complete_dos # bs = run.get_band_structure("Band/KPOINTS") bsdosplot = BSDOSPlotter(