def plot_dos(args): v = Vasprun(args.filename[0]) dos = v.complete_dos all_dos = OrderedDict() all_dos["Total"] = dos structure = v.final_structure if args.site: for i in xrange(len(structure)): site = structure[i] all_dos["Site " + str(i) + " " + site.specie.symbol] = \ dos.get_site_dos(site) if args.element: syms = [tok.strip() for tok in args.element[0].split(",")] all_dos = {} for el, dos in dos.get_element_dos().items(): if el.symbol in syms: all_dos[el] = dos if args.orbital: all_dos = dos.get_spd_dos() plotter = DosPlotter() plotter.add_dos_dict(all_dos) if args.file: plotter.get_plot().savefig(args.file[0]) else: plotter.show()
def plot_dos(args): v = Vasprun(args.filename[0]) dos = v.complete_dos all_dos = OrderedDict() all_dos["Total"] = dos structure = v.final_structure if args.site: for i in range(len(structure)): site = structure[i] all_dos["Site " + str(i) + " " + site.specie.symbol] = \ dos.get_site_dos(site) if args.element: syms = [tok.strip() for tok in args.element[0].split(",")] all_dos = {} for el, dos in dos.get_element_dos().items(): if el.symbol in syms: all_dos[el] = dos if args.orbital: all_dos = dos.get_spd_dos() plotter = DosPlotter() plotter.add_dos_dict(all_dos) if args.file: plotter.get_plot().savefig(args.file[0]) else: plotter.show()
def dos_graph_soc(rawdatadir, savedir): dosrun = Vasprun("{}/vasprun.xml".format(rawdatadir), soc=True, parse_dos=True) dos = dosrun.complete_dos orbitals = { "s": Orbital.s, "p_y": Orbital.py, "p_z": Orbital.pz, "p_x": Orbital.px, "d_xy": Orbital.dxy, "d_yz": Orbital.dyz, "d_z2-r2": Orbital.dz2, "d_xz": Orbital.dxz, "d_x2-y2": Orbital.dx2 } spinor_component = { "mtot": SpinNonCollinear.mtot, "mx": SpinNonCollinear.mx, "my": SpinNonCollinear.my, "mz": SpinNonCollinear.mz } for m in spinor_component: dosplot = DosPlotter() if m == "mtot": dosplot.add_dos("Total DOS with SOC", dos.tdos) dosplot.add_dos_dict(dos.get_element_dos()) plt = dosplot.get_plot(xlim=[-3, 3], soc=True, spinor_component=spinor_component[m], element_colors=True) plt.grid() plt.savefig("{}/DOSGraph_{}_{}".format(savedir, m, "DOS by Element with SOC")) plt.close() for m in spinor_component: dosplot = DosPlotter() if m == "mtot": dosplot.add_dos("Total DOS with SOC", dos.tdos) dosplot.add_dos_dict(dos.get_orbital_dos()) plt = dosplot.get_plot(xlim=[-3, 3], soc=True, spinor_component=spinor_component[m]) plt.grid() plt.savefig("{}/DOSGraph_{}_{}".format(savedir, m, "DOS by Orbital with SOC")) plt.close() # Get detailed info about band gap (source: vasprun.xml) dos_graph_soc.e_fermi = float(dosrun.efermi) dos_graph_soc.electronic_gap = \ dosrun.tdos.get_gap_alt(xlim=[-3,3],e_fermi=dos_graph_soc.e_fermi, tol=0.001,abs_tol=False, spin=SpinNonCollinear.mtot) return
class DosPlotterTest(unittest.TestCase): def setUp(self): with open(os.path.join(test_dir, "complete_dos.json"), "r", encoding='utf-8') as f: self.dos = CompleteDos.from_dict(json.load(f)) self.plotter = DosPlotter(sigma=0.2, stack=True) def test_add_dos_dict(self): d = self.plotter.get_dos_dict() self.assertEqual(len(d), 0) self.plotter.add_dos_dict(self.dos.get_element_dos(), key_sort_func=lambda x: x.X) d = self.plotter.get_dos_dict() self.assertEqual(len(d), 4) def test_get_dos_dict(self): self.plotter.add_dos_dict(self.dos.get_element_dos(), key_sort_func=lambda x: x.X) d = self.plotter.get_dos_dict() for el in ["Li", "Fe", "P", "O"]: self.assertIn(el, d) # Minimal baseline testing for get_plot. not a true test. Just checks that # it can actually execute. def test_get_plot(self): # Disabling latex is needed for this test to work. from matplotlib import rc rc('text', usetex=False) self.plotter.add_dos_dict(self.dos.get_element_dos(), key_sort_func=lambda x: x.X) plt = self.plotter.get_plot() self.plotter.save_plot("dosplot.png") self.assertTrue(os.path.isfile("dosplot.png")) os.remove("dosplot.png")
def plot_dos_dict(complete_dos, d, xlim=(-3, 3), **kwargs): """ Plot DOS dict with pymatgen. The dict is most likely generated with the methods of the pymatgen CompleteDos class. Parameters ---------- complete_dos : CompleteDos object. d : TYPE Dict of DOS. xlim : (tuple), optional Limits for x axis. The default is (-3,3). **kwargs : (dict) Arguments for DosPlotter in pymatgen. Returns ------- plt : Matplotlib object. """ dos_plotter = DosPlotter(**kwargs) for k in d: dos_plotter.add_dos(k, d[k]) eg = complete_dos.get_gap() plt = dos_plotter.get_plot(xlim=(xlim[0], eg + xlim[1])) return plt
class DosPlotterTest(unittest.TestCase): def setUp(self): with open(os.path.join(test_dir, "complete_dos.json"), "r", encoding='utf-8') as f: self.dos = CompleteDos.from_dict(json.load(f)) self.plotter = DosPlotter(sigma=0.2, stack=True) def test_add_dos_dict(self): d = self.plotter.get_dos_dict() self.assertEqual(len(d), 0) self.plotter.add_dos_dict(self.dos.get_element_dos(), key_sort_func=lambda x: x.X) d = self.plotter.get_dos_dict() self.assertEqual(len(d), 4) def test_get_dos_dict(self): self.plotter.add_dos_dict(self.dos.get_element_dos(), key_sort_func=lambda x: x.X) d = self.plotter.get_dos_dict() for el in ["Li", "Fe", "P", "O"]: self.assertIn(el, d) # Minimal baseline testing for get_plot. not a true test. Just checks that # it can actually execute. def test_get_plot(self): # Disabling latex is needed for this test to work. from matplotlib import rc rc('text', usetex=False) self.plotter.add_dos_dict(self.dos.get_element_dos(), key_sort_func=lambda x: x.X) plt = self.plotter.get_plot() self.plotter.save_plot("dosplot.png") self.assertTrue(os.path.isfile("dosplot.png")) os.remove("dosplot.png")
def get_dos_plot(args): """ Plot DOS. Args: args (dict): Args from argparse. """ v = Vasprun(args.dos_file) dos = v.complete_dos all_dos = OrderedDict() all_dos["Total"] = dos structure = v.final_structure if args.site: for i, site in enumerate(structure): all_dos["Site " + str(i) + " " + site.specie.symbol] = dos.get_site_dos(site) if args.element: syms = [tok.strip() for tok in args.element[0].split(",")] all_dos = {} for el, dos in dos.get_element_dos().items(): if el.symbol in syms: all_dos[el] = dos if args.orbital: all_dos = dos.get_spd_dos() plotter = DosPlotter() plotter.add_dos_dict(all_dos) return plotter.get_plot()
class MyDynamicMplCanvas(MyMplCanvas): """A canvas that updates itself every second with a new plot.""" def __init__(self, *args, **kwargs): MyMplCanvas.__init__(self, *args, **kwargs) self.dsp = DosPlotter() def update_figure(self, txt): # Build a list of 4 random integers between 0 and 10 (both inclusive) self.axes.clear() with open(txt) as f: ef = float(f.readline().split()[-2]) arr = [r.split() for r in f.readlines()] arr = np.array(arr) arr = arr.astype(np.float) self.dos = Dos(ef, arr[:, 0], {Spin.up: arr[:, 1]}) self.dsp.add_dos('tdos', self.dos) self.dsp.get_plot(plt=self.axes) self.draw()
def plot_dos(self, sigma=0.05): """ plot dos Args: sigma: a smearing Returns: a matplotlib object """ plotter = DosPlotter(sigma=sigma) plotter.add_dos("t", self._bz.dos) return plotter.get_plot()
def plot_dos(self, sigma=0.05): """ plot dos Args: sigma: a smearing Returns: a matplotlib object """ plotter = DosPlotter(sigma=sigma) plotter.add_dos("t", self._bz.dos) return plotter.get_plot()
Si3.set_calculator(calc3) en3 = Si2.get_potential_energy() # *************************************************************************************************** os.chdir('..') dosrun = Vasprun("DOS/vasprun.xml", parse_dos=True) dos = dosrun.complete_dos print("E_Fermi=%f%3s" % (dosrun.efermi, 'eV')) # 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")
import os from collections import OrderedDict from pymatgen.core.periodic_table import Element vasp_dir = os.path.dirname(os.path.abspath(__file__)) vasp_run = Vasprun(os.path.join(vasp_dir, "vasprun.xml")) dos = vasp_run.complete_dos all_dos = OrderedDict() all_dos["Total"] = dos elem = dos.get_element_dos() print elem.keys() from copy import deepcopy AgSe = elem[Element('Ag')].__add__(elem[Element('Se')]) CH = elem[Element('C')].__add__(elem[Element('H')]) all_dos.update({'Ag+Se':AgSe,'C+H':CH}) plotter = DosPlotter(sigma=0.05) plotter.add_dos_dict(all_dos) plotter.get_plot(xlim=[-3,4],ylim=[0,30],width=12,height=6).savefig(filename="orgo_inorg_dos.pdf",img_format="pdf")
def dos_graph(rawdatadir, savedir, total_dos=True, by_element=False, by_orbital=False): dosrun = Vasprun("{}/vasprun.xml".format(rawdatadir), parse_dos=True) dos = dosrun.complete_dos # Get basic plot dos_graph.e_fermi = float(dosrun.efermi) dos_graph.band_gap = float(dosrun.eigenvalue_band_properties[0]) dosplot = DosPlotter() #dosplot = DosPlotter(sigma=0.1) if total_dos == True: dosplot.add_dos("Total DOS", dos) if by_element == True: dosplot.add_dos_dict(dos.get_element_dos()) if by_orbital == True: dosplot.add_dos_dict(dos.get_spd_dos()) plt = dosplot.get_plot(xlim=[-3, 3], ylim=[-15, 15], element_colors=True) plt.grid() plt.savefig("{}/DOSGraph".format(savedir)) plt.close() # Get plot for comparison with SOC total DOS plot dosplot = DosPlotter() dosplot.add_dos("Total DOS without SOC", dos) dosplot.add_dos_dict(dos.get_element_dos()) plt = dosplot.get_plot_total(xlim=[-3, 3], element_colors=True) plt.grid() plt.savefig("{}/DOSGraph_tot_DOS by Element without SOC".format(savedir)) plt.close() dosplot = DosPlotter() orbitals = { "s": Orbital.s, "p_y": Orbital.py, "p_z": Orbital.pz, "p_x": Orbital.px, "d_xy": Orbital.dxy, "d_yz": Orbital.dyz, "d_z2-r2": Orbital.dz2, "d_xz": Orbital.dxz, "d_x2-y2": Orbital.dx2 } dosplot.add_dos("Total DOS without SOC", dos) dosplot.add_dos_dict(dos.get_orbital_dos()) plt = dosplot.get_plot_total(xlim=[-3, 3]) plt.grid() plt.savefig("{}/DOSGraph_tot_DOS by Orbital without SOC".format(savedir)) plt.close() """ # Get quick info about band gap (source: EIGENVAL) eigenval = Eigenval("{}/EIGENVAL".format(rawdatadir)) dos_graph.band_properties = eigenval.eigenvalue_band_properties """ # Get detailed info about band gap and CB/VB in each spin channel # (source: vasprun.xml) dos_graph.majority_vbm = \ dosrun.tdos.get_cbm_vbm_alt(xlim=[-3,3],e_fermi=dos_graph.e_fermi, tol=0.3,abs_tol=True,spin=Spin.up)[1] dos_graph.majority_cbm = \ dosrun.tdos.get_cbm_vbm_alt(xlim=[-3,3],e_fermi=dos_graph.e_fermi, tol=0.3,abs_tol=True,spin=Spin.up)[0] dos_graph.minority_vbm = \ dosrun.tdos.get_cbm_vbm_alt(xlim=[-3,3],e_fermi=dos_graph.e_fermi, tol=0.3,abs_tol=True,spin=Spin.down)[1] dos_graph.minority_cbm = \ dosrun.tdos.get_cbm_vbm_alt(xlim=[-3,3],e_fermi=dos_graph.e_fermi, tol=0.3,abs_tol=True,spin=Spin.down)[0] dos_graph.majority_gap = \ dosrun.tdos.get_gap_alt(xlim=[-3,3],e_fermi=dos_graph.e_fermi, tol=0.3,abs_tol=True,spin=Spin.up) dos_graph.minority_gap = \ dosrun.tdos.get_gap_alt(xlim=[-3,3],e_fermi=dos_graph.e_fermi, tol=0.3,abs_tol=True,spin=Spin.down) dos_graph.electronic_gap = \ dosrun.tdos.get_gap_alt(xlim=[-3,3],e_fermi=dos_graph.e_fermi, tol=0.3,abs_tol=True,spin=None) return
element_dos = cdos.get_element_dos #element_spd_dos = cdos.get_element_spd_dos(el) 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")
os.chdir( '/home/ksrc5/FTJ/1.bfo/111-dir/junction/sto/vasp/vac/conf3/4.node03/dense_k_dos/again' ) vrun = Vasprun('vasprun.xml') s: Structure = vrun.final_structure cdos = vrun.complete_dos pdos = cdos.pdos doss = dict() num = 16 arr = np.linspace(0, 1, num, endpoint=False) darr = arr[1] - arr[0] for j in arr: densities = [] for i in s.sites: if j + darr > i.c >= j: densities.append(cdos.get_site_dos(i).get_densities()) densities = np.sum(densities, axis=0) doss[f'{j:.2f}'] = Dos(cdos.efermi, cdos.energies, {Spin.up: densities}) dsp = DosPlotter(sigma=0.1) ax_array, fig, plt = get_axarray_fig_plt(None, nrows=num, sharex=True) plt = pretty_plot(12, 6, plt=plt) for i in range(num): dsp.__init__(sigma=0.05) a = doss.popitem() dsp.add_dos(*a) fig.add_subplot(num, 1, i + 1) subplt = dsp.get_plot(xlim=(-1, 2), plt=plt) plt.savefig('figure.png') plt.show()
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()
class Compound: ''' This class is meant to take in a VaspRun object and make it more accessible to get some of its attributes. These attributes are listed below. Typical usage looks like:: var = Compound( VaspRun_object ) compound_mass = var.mass plot = var.getPlot() **Attributes** .. attribute:: vasp The vasp object itself .. attribute:: z (lowercase) The Z component of the compound. i.e. the greatest common denominator of the compound. ex. Ag2Bi2I8 --> AgBiI4 ...... z = 2 .. attribute:: formula The reduced formula of the compound .. attribute:: full_formula The full formula used at the start of the VASP run .. attribute:: elem_List A list of all the elements in the compound ex. Ag2Bi2I8 --> ['Ag', 'Bi', 'I'] .. attribute:: mass The total mass of the object given in AUs or Daltons .. attribute:: volume The volume of the cell containing the compound given in Angstroms cubed .. attribute:: density The density of the compound. This is multiplied by 1.66054 to make the units grams/cm^3 .. attribute:: neighbors A list of each of the atoms nearest neighbors to one another. See .. attribute:: latConst A list of the 'a b c' lattice constants in the compound i.e. [a const, b const, c const] **Methods** .. method:: getPlot() Returns a Density of states plot ''' def __init__(self, vasp): self.vasp = vasp self.z = self.getGCD() self.formula = self.getElem() self.full_formula = self.getElem(False) self.elem_List = self.elList() self.mass = Mass(vasp.atomic_symbols) self.volume = vasp.final_structure.volume self.density = self.mass / self.volume * 1.66054 self.neighbors = nearNeighbors(vasp) self.latConst = self.getLatConst() self.plot = DosPlotter() def elList(self): lis = [] temp = {} for x in self.vasp.atomic_symbols: if x in temp: temp[x] += 1 else: temp[x] = 1 for x in temp: lis.append(x) return lis def getNeighbor(self, el1, el2): return self.neighbors[el1 + '-' + el2] def getGCD(self): el = {} for x in self.vasp.atomic_symbols: if x in el: el[x] += 1 else: el[x] = 1 return gcd.reduce([el[x] for x in el]) def getElem(self, pretty=True): string = "" el = {} for x in self.vasp.atomic_symbols: if x in el: el[x] += 1 else: el[x] = 1 for x in el: if pretty: num = int(el[x] / self.z) else: num = int(el[x]) if num == 1: string += x else: string += x + str(num) return string def getPlot(self): self.plot.add_dos("Total Dos", self.vasp.complete_dos) return self.plot.get_plot() def getLatConst(self): return self.vasp.final_structure.lattice.abc
#!/nfshome/villa/anaconda3/bin/python """ Spyder Editor This is a temporary script file. """ import os from pymatgen.core.periodic_table import Element from pymatgen.io.vasp.outputs import Vasprun from pymatgen.io.vasp.inputs import Poscar from pymatgen.electronic_structure.plotter import DosPlotter complete_dos = Vasprun('vasprun.xml').complete_dos partial_dos = complete_dos.get_spd_dos() dos_plotter = DosPlotter() dos_plotter.add_dos('Total_dos', complete_dos) for orbital in partial_dos: dos_plotter.add_dos(orbital, partial_dos[orbital]) plt = dos_plotter.get_plot(xlim=(-10, 10)) plt.show()
from pymatgen.analysis.surface_analysis import WorkFunctionAnalyzer l = Locpot.from_file('LOCPOT') s = Poscar.from_file('CONTCAR') wf = WorkFunctionAnalyzer(s.structure, l.get_average_along_axis(1), efermi, shift=0) loc_vac = wf.vacuum_locpot for i in element_dos: element_dos[i].efermi = loc_vac plotter.add_dos_dict(element_dos) plt = plotter.get_plot(xlim=[-9, 1]) plt.plot([efermi - loc_vac, efermi - loc_vac], plt.ylim(), 'b--', linewidth=2, label='EF') plt.xlabel('Energies - Vac(eV)') plt.legend() leg = plt.gca().get_legend() ltext = leg.get_texts() # all the text.Text instance in the legend plt.setp(ltext, fontsize=30) plt.tight_layout() plt.savefig('dos.png') plt.show()
def plot_dos(self): plotter = DosPlotter(sigma=0.05) plotter.add_dos("t", self._bz.dos) plotter.get_plot().show()
out = Outcar('./OUTCAR') print('Total Magnetic Moment:', out.total_mag) if make_dosplot: # read in BSDOSPlotter function to plot DOS and BS from pymatgen.electronic_structure.plotter import DosPlotter # make and save a plot of the band structure and DOS dos = vsp.complete_dos energy_range = (-10, 7) # eV, change if desired to change plotting range # create DosPlotter object with smearing edosplot = DosPlotter(sigma=dos_smearing) # plot Total DOS and element-projected dos edosplot.add_dos("Total DOS", dos) edosplot.add_dos_dict(dos.get_element_dos()) plt = edosplot.get_plot(xlim=energy_range) plt.plot((-20, 20), (0, 0), 'k--') plt.savefig('Element_DOS_plot.png') # create DosPlotter object with smearing odosplot = DosPlotter(sigma=dos_smearing) # plot Total DOS and orbital-projected dos odosplot.add_dos("Total DOS", dos) odosplot.add_dos_dict(dos.get_spd_dos()) plt = odosplot.get_plot(xlim=energy_range) plt.plot((-20, 20), (0, 0), 'k--') plt.savefig('Orbital_DOS_plot.png') print('Generated DOS plots')
from pymatgen.io.vasp.outputs import Vasprun from pymatgen.electronic_structure.plotter import DosPlotter from collections import OrderedDict vaspout = Vasprun("vasprun.xml") dos = vaspout.complete_dos all_dos = OrderedDict() all_dos["Total"] = dos plt = DosPlotter() plt.add_dos_dict(all_dos) plt = plt.get_plot(xlim=[-10,10],ylim=[0,1.5]) plt.savefig('dos.pdf')
def plot_dos(self): plotter = DosPlotter(sigma=0.05) plotter.add_dos("t", self._bz.dos) plotter.get_plot().show()