autodataming的个人博客分享 http://blog.sciencenet.cn/u/autodataming

博文

Pymol代码分析:cmd.save 的分析

已有 4667 次阅读 2016-9-7 17:01 |个人分类:DrugDesign|系统分类:科研笔记

from pymol import cmd

cmd.save('1.pdb','objcetname')

从这我们可以知道pymol 是一个包,cmd 是一个模块

我们在PyMol/modules文件夹下能找到pymol的包,在pymol 包中能找到cmd.py的模块,

当我们直接在save.py 文件中直接搜save的定义的时候没有找到,则save一定是从其他文件中导入进来的,我们 搜索 'import save',没有发现,则save 一定是import *的形式进来的,从模块的命名能很快获得线索,from .api import * ,打开api.py 文件,果然找到了save的来源,from .exporting import save, 在exporting.py中果然找到了save的定义。


def save(filename, selection='(all)', state=-1, format='', ref='',
            ref_state=-1, quiet=1, partial=0,_self=cmd):
       '''
DESCRIPTION

   "save" writes content to a file.
   
USAGE

   save filename [, selection [, state [, format ]]]

ARGUMENTS

   filename = string: file path to be written

   selection = string: atoms to save {default: (all)}

   state = integer: state to save {default: -1 (current state)}
   
PYMOL API

   cmd.save(string file, string selection, int state, string format)

NOTES

   The file format is automatically chosen if the extesion is one of
   the supported output formats: pdb, pqr, mol, sdf, pkl, pkla, mmd, out,
   dat, mmod, cif, pov, png, pse, psw, aln, fasta, obj, mtl, wrl, dae, idtf,
   or mol2.

   If the file format is not recognized, then a PDB file is written
   by default.

   For molecular files and where applicable and supported:
   
   * if state = -1 (default), then only the current state is written.

   * if state = 0, then a multi-state output file is written.
   
SEE ALSO

   load, get_model
       '''
       import gzip

       quiet = int(quiet)
       do_gzip = False

       # preprocess selection
       selection = selector.process(selection)
       #  
       r = DEFAULT_ERROR

       if format=='':
           ext_list = filename.lower().rsplit('.', 2)
           if ext_list[-1] == 'gz':
               do_gzip = True
               ext = ext_list[-2]
           else:
               ext = ext_list[-1]

           if ext in ['cif', 'pqr', 'mol', 'sdf', 'pkl', 'xyz', 'pov',
                   'png', 'aln', 'fasta', 'obj', 'mtl', 'wrl', 'dae', 'idtf',
                   'mol2']:
               format = ext
           elif ext in ["pdb", "ent"]:
               format = 'pdb'
           elif ext in ["mmod", "mmd", "out", "dat"]:
               format = 'mmod'
           elif ext in ["pse", "psw"]:
               format = 'pse'
           elif ext in ["pze", "pzw"]:
               do_gzip = True
               format = 'pse'
           else:
               if not quiet:
                   print(" Save-Warning: Unrecognized file type -- defaulting to PDB format.")
               format='pdb'

       filename = _self.exp_path(filename)

       func_type1 = {
           'cif': get_cifstr, # mmCIF
           'xyz': get_xyzstr,
           'fasta': get_fastastr,
           'aln': get_alnstr,
       }

       func_type2 = {
           'pdb': get_pdbstr,
           'pqr': get_pqrstr,
           'sdf': get_sdfstr,
           'mol2': get_mol2str,
       }

       def safe_getitem(tup, idx):
           return tup[idx] if tup else None

       func_type3 = {
           'dae': _self.get_collada,
           'wrl': _self.get_vrml,
           'mtl': lambda: safe_getitem(_self.get_mtl_obj(), 0),
           'obj': lambda: safe_getitem(_self.get_mtl_obj(), 1),
           'pov': _self.get_povray,
           'idtf': _self.get_idtf,
       }

       func_type4 = {
           'mmod': io.mmd.toFile,
           'pkl': io.pkl.toFile, # binary pickle
           'pkla': lambda model, filename: io.pkl.toFile(model, filename, bin=0), # ascii pickle
           'mol': io.mol.toFile,
       }

       contents = None

       if format in func_type1:
           contents = func_type1[format](selection, state, quiet, _self=_self)
       elif format in func_type2:
           contents = func_type2[format](selection, state, ref, ref_state, quiet, _self=_self)
       elif format in func_type3:
           contents = func_type3[format]()
           if isinstance(contents, tuple):
               contents = ''.join(contents)
       elif format in func_type4:
           func_type4[format](_self.get_model(selection, state, ref, ref_state), filename)
           r = DEFAULT_SUCCESS
       elif format=='pse': # PyMOL session
           filename = filename.replace("\","/") # always use unix-like path separators    
           _self.set("session_file",filename,quiet=1)
           if '(' in selection: # ignore selections
               selection = ''
           if not quiet:
               print(" Save: Please wait -- writing session file...")
           contents = cPickle.dumps(_self.get_session(selection, partial, quiet), 1)
       elif format=='png':
           return _self.png(filename, quiet=quiet)

       if cmd.is_string(contents):
           if not isinstance(contents, bytes):
               contents = contents.encode()
           with (gzip.open if do_gzip else open)(filename, 'wb') as handle:
               handle.write(contents)
           r = DEFAULT_SUCCESS
           
       if _self._raising(r,_self): raise QuietException

       if not quiet:
           if r == DEFAULT_SUCCESS:
               print(' Save: wrote "' + filename + '".')
           else:
               print(' Save-Error: no file written')

       return r

   # mmCIF export

   re_cifsimpledatavalue_match = re.compile(r'[^_#$\'"\[\];]\S*$').match
   re_cifendsinglequote_search = re.compile(r"'s").search
   re_cifenddoublequote_search = re.compile(r'"s').search

----------------------

之所以这么麻烦,因为github 不支持精确搜索,我建议搭建,直接把pymol中的modules 文件夹全部导入到本地编辑器中如atom,Ultraedit,UES,sublimtext。 这样可以很快定位到想要的代码。

pymol 中所有的python代码都在modules文件,是学习python的无尽宝藏。



https://blog.sciencenet.cn/blog-950202-1001458.html

上一篇:pymol插件开发 内在widget 组件的的关系
下一篇:pymol 安装模块
收藏 IP: 140.206.57.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-4-19 13:05

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部