단백질 구조를 가지고 놀다보면 디렉토리에 PDB 파일이 쌓이게 되고..가끔은 이 파일이 무슨 구조의 파일인지조차 헷갈리는 경우가 있다.
물론 일일히 PyMOL과 같은 프로그램으로 열어보든지 아니면 PDB 사이트에서 검색을 해보셈…할수도 있겠으나 한두개면 모르겠는데 갯수가 늘어나면 난감하기 마련.
“디렉토리에 들어있는 PDB 파일을 한번에 몽땅 그림으로 보여주는 방법이 없을까?”
그런 방법 별로 생각이 안나네염.ㅋㅋ 그러나 이제 생겼음.
#!/usr/bin/python # # Batch Pymol Renderer # Require Python 2.7 (argparse) and Pymol # # import sys, subprocess, re, os, glob import argparse def pdbparsing(filename, regex): # # Parse pdb content and extract using regex # if os.path.exists(filename): pdb = open(filename) pdbcontent = pdb.readlines() matched = '' matchedcount=0 reg = re.compile(regex) for line in pdbcontent: match = reg.match(line) if match: if matchedcount==0: gap = " " else: gap = "" matched = matched+gap+match.group(1).strip() return (matched) else: print "{0} is not found!".format(filename) sys.exit() def htmlout(description): # # Generate render.html which display rendered png files # # htmlheader = """ <!DOCTYPE html> <html> <head> <title>List</title> <meta charset='utf-8'> </head> <style> </style> <body> """ imgtag = """ <img src="./{0}"> <p><a href="http://www.rcsb.org/pdb/explore/explore.do?structureId={1}">{2}</a></p> """ htmlfooter = """ </body> </html> """ htmloutput = open('render.html','w') htmloutput.write(htmlheader) for pdb,desc in description.items(): htmloutput.write(imgtag.format(pdb[:-4]+".png", pdb[:len(pdb)-4], pdb[:len(pdb)-4]+":"+desc)) htmloutput.write(htmlfooter) htmloutput.close() def main(arglist): # # PyMol executable path # In cases of MacPymol, It assumed that pymol is installed in 'Application' folder. # Other cases, plase set up the exact location of PyMOL executable # PyMOLPath = '/Applications/MacPyMOL.app/Contents/MacOS/MacPyMol' if len(arglist.file)>0: subjectList = arglist.file else: subjectList = glob.glob('*.pdb') if len(subjectList)>0 : pymolLoadingFile = open('render.pml','w') pymolLoadingFile.write('bg_color white\n') description = {} style = "cartoon" #Defaults if arglist.ribbon : style = "ribbon" if arglist.line : style = "line" if arglist.stick : style = "stick" if arglist.view: if os.path.exists(arglist.view): f = open(arglist.view) view = f.readlines() if re.match("^set_view",view[0]): for line in view: pymolLoadingFile.write(line) for pdb in subjectList: if os.path.exists(pdb): print pdb pymolLoadingFile.write("load {0}/{1}\n".format(os.getcwd(),pdb)) pymolLoadingFile.write("hide all\n") pymolLoadingFile.write("show {0}, {1}\n".format(style, pdb[:-4])) if arglist.cbc: pymolLoadingFile.write("util.cbc\n") else: pymolLoadingFile.write("spectrum count,rainbow,{0}\n".format(pdb[:-4])) if arglist.surface: pymolLoadingFile.write("show surface,{0}\n".format(pdb[:-4])) if not arglist.view: pymolLoadingFile.write("orient {0}\n".format(pdb[:-4])) if arglist.ray: pymolLoadingFile.write("ray\n") pymolLoadingFile.write("png {0}.png\n".format(pdb[:-4])) description[pdb]=pdbparsing(pdb, '^TITLE [ \d](.*)$') pymolLoadingFile.close() print "Running PyMol..." p = subprocess.Popen([PyMOLPath,'-c','render.pml'], stdout=subprocess.PIPE) p_stdout = p.stdout.read() htmlout(description) else: print "Usage : render.py" sys.exit() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-r', '--ribbon', action='store_true', dest='ribbon',default=False, help='Draw as ribbon') parser.add_argument('-l', '--line', action='store_true', dest='line',default=False, help='Draw as Line') parser.add_argument('-t', '--stick', action='store_true', dest='stick',default=False, help='Draw as Stick') parser.add_argument('-s', '--surface', action='store_true', dest='surface',default=False, help='Draw as Surface') parser.add_argument('-c', '--color_by_chain', action='store_true', dest='cbc',default=False, help='Color by Chain') parser.add_argument('-rt', '--ray_trace', action='store_true', dest='ray',default=False, help='Ray tracing') parser.add_argument('-f', '--files', nargs='*', dest='file',default=[], help='File to process') parser.add_argument('-v', '--fixed_view', action='store', dest='view') results = parser.parse_args() main(results)
위 스크립트를 render.py 등으로 저장하고 실행권한을 준다음 PATH가 설정되어 있는 디렉토리에 넣든 pdb 가 디글거리는 파일에 넣든지 하시고,
Python 2.7에서 지원되는 argparse 모듈을 사용하고 있으므로 Python 2.7 이상을 사용하든지 argparse를 설치. 그리고 PyMol 이 설치되어 있어야 하고, MacPyMol 이 아닌 경우에는 75라인의 PyMOLPath = '/Applications/MacPyMOL.app/Contents/MacOS/MacPyMol' 을 자신의 PyMol 설치경로로 바꾸어 주어야 한다
실행옵션을 보면
./render.py -h usage: render.py [-h] [-r] [-l] [-t] [-s] [-c] [-rt] optional arguments: -h, --help show this help message and exit -r, --ribbon Draw as ribbon -l, --line Draw as Line -t, --stick Draw as Stick -s, --surface Draw as Surface -c, --color_by_chain Color by Chain -rt, --ray_trace Ray tracing
일단 아무 옵션 없이 render.py 를 실행시켜보면 render.pml 이라는 파일이 생성되고 자동적으로 스크립트내에서 PyMOL 을 실행시킨후 디렉토리내에 있는 모든 PDB를 하나씩 부른후 이를 png 로 저장한다.
그게 다가 아니라 render.html 이라는 html 형식의 카탈로그를 만들어줌. 설명을 클릭하면 rcsb pdb의 해당 pdb 페이지로 이동.
여러가지 옵션을 제공하는데 (디폴트는 cartoon 방식의 렌더링이고, 색 지정은 N말단 – 청색 C말단 – 적색의 스펙트럼)
./render.py -r
./render.py -s
surface로 렌더링 (다른 표현방식에 비해 장시간이 걸리는 것에 유의)
./render.py -c
color by chain (chain별로 다른 color지정하여 렌더링)방식으로 색지정 변환.
./render.py -c -s
surface로 rendering하면서 color by chain
./render.py -rt
Raytracing (고품질의 렌더링이 가능하나 시간이 매우 오래 걸림에 유의)
추가로 부연설명하면
1. PyMol을 Python Script에서 제어하는 방법으로 가장 속편한 방법이라면 여기서 쓰는 방법처럼 PyMol script (위의 예에서는 Render.pml) 를 만들고 PyMol을 수행하여 작업을 수행하는 것임. 이렇게 생성된 스크립트를 대충 살펴보면
bg_color white #바탕색 하얀색 load /Users/suknamgoong/Dropbox/pdbsearch/S_1G9O.pdb #로딩. hide all #몽땅지우고 show cartoon, S_1G9O #S_1G9O이라는 pdb를 cartoon으로 그림 util.cbc #color by chain orient S_1G9O #최적의 위치로 카메라위치 옮김 png S_1G9O.png #S_1G90.png라는 이름으로 그림 png로 저장 .....반복
2. PyMol 을 커맨드 라인에서 수행하려면
PyMol -c script.pml
와 같은 방식으로 수행하면 편함.