24小时热门版块排行榜    

查看: 2259  |  回复: 9
【奖励】 本帖被评价8次,作者hakuna增加金币 6.8
当前只显示满足指定条件的回帖,点击这里查看本话题的所有回帖

hakuna

木虫 (知名作家)


[资源] 【分享】code for ploting VASP output__from Panda Blog已有1人参与

此内容转自panda的博客,尽量保持原形,有兴趣的话自己研究吧

Plotting the EIGNEVAL file
Now that we have written the module we simply import it like this:
import eigenval_reader as er
Now the entirety of the source code is simply import statements and matplotlib directives. In other words, all of the programming logic is self-contained within the module, which can be used again and again, from the command line or within your ide of choice. See how much cleaner things are when the logic is separated on a lower-level and the plotting is handled on a higher level? Modules are a really nice way to accomplish whatever task you wish to accomplish in Python. In fact, matplotlib, numpy, and scipy are just huge modules that we interact with in Python at a higher level just as the very simple module given in the previous post that we interact with in the source code below!
**************
CODE:
#!/usr/bin/python  
import sys  
from math import *
import numpy  
from numpy import *
from numpy import dot  
import csv  
import re  
from matplotlib import *
from pylab import plot, show, ylim, xlim, yticks, xlabel, ylabel  
import matplotlib.path as mpath  
import matplotlib.patches as mpatches  
import matplotlib.pyplot as plt  
from matplotlib.font_manager import FontProperties  
import matplotlib  
import eigenval_reader as er  
if (__name__ == '__main__'):  
     filename = 'EIGENVAL'
     if len(sys.argv) == 2:  
        filename = sys.argv[1]  
     else:  
         print("Defaulting filename to 'EIGENVAL', if you wish to specify another filename on the command prompt do it like this: plot_eigenval.py myfilename")  
   
    parser = er.EigenvalParser()  
    kpoints = parser.parse(filename)  
    rcParams['lines.linewidth'] = 4.0
    rcParams['font.weight'] = "heavy"
    rcParams['axes.linewidth'] = 4.0

    rcParams['xtick.major.size'] = 0.0
     rcParams['xtick.minor.size'] = 0.0

     rcParams['ytick.major.size'] = 0.0

     rcParams['ytick.minor.size'] = 0.0   

    for band in er.get_bands(kpoints):  
         plot(range(0,len(band)), band, 'k')  
     xlim(0,60)  
    ylim(-8,4)  
     plt.title("Band Structure")  
     xlabel("K-Points")  
     ylabel("Energy(eV)")  
     plt.show()


****************

Writing a Python Module for the VASP EIGENVAL file
Sometimes you will have tasks that need to be performed again and again. In this case, it is oftentimes advantageous to write a module. In python, modules are imported just like libraries. By separating your code in this manner, you benefit in flexibility as well as in producing code that is reusable. I have written a module for parsing the VASP EIGENVAL file, but you can write a module for anything you wish.
***************
CODE:
import re  

02   

03 class EigenvalReader:  

04     def __init__(self):  

05         self.listeners = {}  

06   

07     def add_listener(self, event_name, callback):  

08         if (not self.listeners.has_key(event_name)):  

09             self.listeners[event_name] = []  

10         self.listeners[event_name].append(callback)  

11   

12     def __raise__(self, event_name, args):  

13         if not self.listeners.has_key(event_name):  

14             return

15   

16         callbacks = self.listeners[event_name]  

17         if callbacks != None:  

18             for c in callbacks:  

19                 c(self, args)  

20   

21     def read_file(self, eigen_file):  

22         f = open(eigen_file)  

23         for i in range(0,5):  

24             f.readline()  

25   

26         throwaway, kpoint_count, band_count = f.readline().split()  

27         self.__raise__('ON_KPOINT_COUNT', kpoint_count)  

28         self.__raise__('ON_BAND_COUNT', band_count)  

29   

30         # Blank Line  

31         f.readline()  

32   

33         # End of File (EOF)  

34         eof = False

35         while (not eof):  

36             line = f.readline()  

37             if line == None:  

38                 eof = True

39                 continue

40             try:  

41                 x,y,z,weight = line.split()  

42                 self.__raise__('ON_KPOINT', { "x": x, "y": y, "z": z, "weight": weight })  

43             except:  

44                 print('failed to split line: ' + line)  

45   

46             for i in range(0, int(band_count)):  

47                 line = f.readline()  

48                 try:  

49                     id, energy = line.split()  

50                     self.__raise__('ON_BAND', { 'id': id, 'energy': float(energy) })  

51                 except:  

52                     print('failed to get band info from: ' + line)  

53   

54             line = f.readline()  

55             if line == '':  

56                 eof = True

57   

58 class EigenvalParser:  

59     def parse(self, filename):  

60         self.kpoints = []  

61         reader = EigenvalReader()  

62         reader.add_listener('ON_KPOINT', self.__on_kpoint__)  

63         reader.add_listener('ON_BAND', lambda reader, band: self.kpoints[-1]['bands'].append(band))  

64   

65         reader.read_file(filename)  

66   

67         return self.kpoints  

68   

69     def __on_kpoint__(self, reader, kpoint):  

70         kpoint['bands'] = []  

71         self.kpoints.append(kpoint)  

72   

73 def get_bands(kpoints):  

74     bands = [[] for b in range(0,len(kpoints[0]['bands']))]  

75   

76     for kp in kpoints:  

77         kp_bands = kp['bands']  

78         for kp_band in kp_bands:  

79             bands[int(kp_band['id']) - 1].append(kp_band['energy'])  

80   

81     return bands


*****************
In this example, first the re module in imported, as regular expression pattern matching is typically the easiest way to parse a file in Python. After that a class is defined. In that class, we define an event handler. After that, the file is opened and parsed using the re module. The “try” “except” clauses are included so that if the arrays are not loaded into memory then an exception is thrown and an error is printed. It is always a good idea to add break points like this in your code. The class EignevalReader reads the file and the class EignevalParser parses the file and splits the file data neatly into arrays. The next post will deal with using this module to plot the EIGENVAL file.


Parsing VASP PROCAR file
CODE:
#!/usr/bin/python  

002 import sys  

003 from math import *

004 import numpy  

005 from numpy import *

006 from numpy import dot  

007 import csv  

008 import re  

009 from matplotlib import *

010 from pylab import plot, show, ylim, xlim, yticks, xlabel, ylabel  

011 import matplotlib.path as mpath  

012 import matplotlib.patches as mpatches  

013 import matplotlib.pyplot as plt  

014 from matplotlib.font_manager import FontProperties  

015 import matplotlib  

016   

017 def getMeta(line):  

018  metaMatcher = re.compile("#[^:]+:([^#]+)#[^:]+:([^#]+)#[^:]+:(.+)$")  

019  m = metaMatcher.match(line)  

020  kpointsCount = int(m.group(1))  

021  bandsCount = int(m.group(2))  

022  ionsCount = int(m.group(3))  

023  return (kpointsCount, bandsCount, ionsCount)  

024   

025 def readKPoint(stream, bandsCount, ionsCount):  

026  kpointHeaderMatcher = re.compile("\s*k-point[^:]+:\s*([^\s]+)\s*([^\s]+)\s*([^\s]+)")  

027  line = stream.readline()  

028  while (not kpointHeaderMatcher.match(line)):  

029  line = stream.readline()  

030  kpointHeaderLine = line  

031  m = kpointHeaderMatcher.match(kpointHeaderLine)  

032  kpoint_x = float(m.group(1))  

033  kpoint_y = float(m.group(2))  

034  kpoint_z = float(m.group(3))  

035   

036  bandHeaderMatcher = re.compile(".+energy\s+([^#]+)# occ\.\s(.+)$")  

037   

038  bands = []  

039  for i in range(0,bandsCount):  

040  line = stream.readline()  

041  while (not bandHeaderMatcher.match(line)):  

042  line = stream.readline()  

043  bandHeaderLine = line  

044  energy = float(bandHeaderMatcher.match(line).group(1))  

045   

046  orbitalHeaderMatcher = re.compile("ion\s+s.+tot$")  

047  line = stream.readline()  

048  while (not orbitalHeaderMatcher.match(line)):  

049  line = stream.readline()  

050  orbitalHeaderLine = line  

051   

052  orbitals = []  

053  for j in range(0,ionsCount):  

054  line = stream.readline()  

055  orbitalAssignmentText = line.split()  

056  orbitals.append(orbitalAssignmentText)  

057   

058  bands.append({ "energy": energy,"orbitals": orbitals })  

059  return { "kpoint_x": kpoint_x, "kpoint_y": kpoint_y, "kpoint_z": kpoint_z, "bands": bands }  

060   

061 def readFile(procar):  

062  f = open(procar, "r")  

063  f.readline() # throwaway  

064  metaLine = f.readline() # metadata  

065  kpointsCount, bandsCount, ionsCount = getMeta(metaLine)  

066  kpoints = []  

067  for i in range(0,kpointsCount):  

068  kpoint = readKPoint(f, bandsCount, ionsCount)  

069  kpoints.append(kpoint)  

070  return (kpoints, bandsCount, ionsCount)  

071   

072 kpoints, bandsCount, ionsCount = readFile("/Working/Eclipse/plotting/Molecule2/PROCAR")  

073 kpointsCount = len(kpoints)  

074   

075 orbitalNames = ["s","py","pz","px","dxy","dyz","dz2","dxz","dx2-y2"]  

076   

077 #print "band,ion,s,py,pz,px,dxy,dyz,dz2,dxz,dx2,tot,energy,kpoint_x,kpoint_y,kpoint_z"  

078 print "kpoint,band,ion,energy,character"

079   

080 energies = []  

081 kpointNums = []  

082 Ef = -4.41823711

083   

084 for i in range(0,bandsCount):  

085  energies.append([])  

086   

087 kpointNum = 1

088 for kpoint in kpoints:  

089  bandNum = 0

090  for band in kpoint["bands"]:  

091  for ion in band["orbitals"]:  

092  character = ""  

093  for i in range(1,9):  

094  if float(ion[i]) > 0:  

095  character += orbitalNames[i-1] + " "

096  kpointNums.append(kpointNum)  

097  energies[bandNum].append(band["energy"]-Ef)  

098  bandNum += 1

099  kpointNum += 1

100   

101 rcParams['lines.linewidth'] = 4.0

102 rcParams['font.weight'] = "heavy"

103 rcParams['axes.linewidth'] = 4.0

104 rcParams['xtick.major.size'] = 0.0

105 rcParams['xtick.minor.size'] = 0.0

106 rcParams['ytick.major.size'] = 0.0

107 rcParams['ytick.minor.size'] = 0.0

108   

109 for i in range(0,bandsCount):  

110  plot(range(0,len(energies[i])),energies[i], 'k')  

111 xlim(0,60)  

112 ylim(-8,4)  

113 plt.title("Band Structure")  

114 xlabel("K-Points")  

115 ylabel("Energy(eV)")  

116 plt.show()

******************
VASP (Vienna Ab-Initio Simulation Package) is a plane wave density functional theory code. When the tag LORBIT is set in the INCAR file, the PROCAR file is generated. The PROCAR file contains the site-projected character of the orbitals (spherical harmonics used). The code above illustrates how to parse and plot the PROCAR file using Python and matplotlib.
Again, the first few lines of code are just the import statements and formatting for matplotlib. The re module is used, in which regular expression pattern matching searches the file for matching characters. More information regarding Python’s re module can be found here. The code could be cleaned up a bit, currently you must manually enter the Fermi energy (it is not parsed from the DOSCAR file), you must manually enter the working directory in which the file resides, etc. Overall though it gets the job done quite nicely with very little coding.
One thing to remember is that depending on which direction you are integrating in the Brillouin Zone, because depending on the crystal structure a scaling length may have to be implemented. You could do this programmatically, but I find it easier to apply the scaling length via pixel scaling, using an image manipulation program like GIMP.

[ Last edited by hakuna on 2010-10-22 at 10:16 ]
回复此楼

» 收录本帖的淘帖专辑推荐

第一性原理相关文档 Photochemistry

» 猜你喜欢

» 本主题相关价值贴推荐,对您同样有帮助:

已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

xiezhong

银虫 (小有名气)


★★★★★ 五星级,优秀推荐

引用回帖:
Originally posted by hakuna at 2010-10-22 10:20:37:
To obtain band structure plots from the GW method, first you have to perform a DFT calculation. The INCAR file I used for DFT on Si looks like this:

ISTART = 0
ISYM = 0
ICHARG = 2
ISMEAR = 0
...

我有个疑问,在进行一、perform a DFT calculation时
(1)为什么不进行弛豫呢?
(2)LORBIT = 11应该是在输出DOSCAR,这里应该不需要DOSCAR吧
二、在After this run completes you are ready to perform the HF-type (HSE06) calculation后
(3)ISYM = 0,为什么设置为0呢
(4)这时发现LORBIT = 11没有了
三、计算完HSE06后
(4)LORBIT = 11又有了,不是计算band的吗,为什么输出DOSCAR吗
真心感谢您,这些我真有些不明白
8楼2011-06-22 11:36:14
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖
相关版块跳转 我要订阅楼主 hakuna 的主题更新
☆ 无星级 ★ 一星级 ★★★ 三星级 ★★★★★ 五星级
普通表情 高级回复(可上传附件)
最具人气热帖推荐 [查看全部] 作者 回/看 最后发表
[基金申请] 求助!请问海外博后依托内地单位申请青基的优劣? 100+3 2280999712 2024-11-15 9/450 2024-11-15 23:08 by dxcharlary
[教师之家] 评正教授需要两个国家级项目,有人用子课题糊弄,结果在评审前资格公示时被举报拿下了 +22 瞬息宇宙 2024-11-12 31/1550 2024-11-15 22:02 by 潇湘之迷
[论文投稿] 国内期刊审稿人数量 +3 新时代核动力驴 2024-11-13 5/250 2024-11-15 20:37 by 新时代核动力驴
[论文投稿] angew三个小修,返修过去已经20多天了没动静,有朋友遇到这种情况吗? +5 迟迟未到场 2024-11-14 5/250 2024-11-15 20:16 by 秦时明月zy
[考博] 随缘读博 一篇中科院一区Top 一篇中科院二区Top 两篇专利 +6 Ricoch4t 2024-11-13 15/750 2024-11-15 19:24 by 青青之洲
[基金申请] 去年七月底入站的还能申请下一批吗? +4 brightwo 2024-11-14 4/200 2024-11-15 14:18 by gazi1111
[精细化工] 同一个反应相同的反应条件,是不是反应结果相差不大? +5 青霉素 2024-11-11 5/250 2024-11-15 13:43 by zyqchem
[硕博家园] reject后小感 +6 sioc-sunj 2024-11-14 8/400 2024-11-15 11:50 by 畅21
[论文投稿] 论文返修状态变成了awaiting AE recommendation 10+3 猪小耍 2024-11-13 12/600 2024-11-15 08:41 by 北京莱茵润色
[论文投稿] OE返修遇到expired +3 隔壁老王来了 2024-11-14 7/350 2024-11-14 20:46 by 隔壁老王来了
[硕博家园] 研究生的生活该是什么样 +4 lqy0719 2024-11-14 4/200 2024-11-14 16:45 by 阿荣喝酒
[有机交流] 同一个反应回流情况不同 20+3 1853846 2024-11-12 3/150 2024-11-14 15:42 by 太阳谷
[硕博家园] 大龄已婚想读博如何 +15 米娅阳 2024-11-11 18/900 2024-11-14 14:18 by xiaomi0401
[教师之家] 处在人生职业的分水岭 +4 otani 2024-11-13 4/200 2024-11-14 14:17 by mddzwo
[找工作] 咨询一下江西的高校待遇,人文氛围怎么样? +5 akslis2024 2024-11-09 5/250 2024-11-14 13:53 by 啄木鸟、
[基金申请] 76批博后基金 +3 feiyi3986 2024-11-14 3/150 2024-11-14 11:50 by puly
[基金申请] 博后面上出结果了 +5 wl87925139 2024-11-14 5/250 2024-11-14 10:26 by kingmax18996
[论文投稿] 论文接受后,编辑部发邮件提醒缺少附件 15+4 上善若水明泪 2024-11-10 4/200 2024-11-12 14:24 by 北京莱茵润色
[论文投稿] 爱思唯尔投稿系统里的通讯作者可以和文章里的通讯作者标注不同吗 +7 Omnissiah 2024-11-10 7/350 2024-11-12 14:07 by holypower
[论文投稿] renewable energy 添加作者 15+3 Hebauwww12 2024-11-09 4/200 2024-11-11 08:42 by 北京莱茵润色
信息提示
请填处理意见